.sync语法糖基本使用
父组件代码如下:
<template> <div> 我是父组件: <input type="text" v-model="msg"> <!-- :value.sync='msg'等价于:value = 'msg' @update:value='msg=$event' --> <son-box :value.sync='msg'/> </div> </template> <script> // 导入子组件 import SonBox from '@/components/son.vue' export default { name:'FatherBox', components:{ SonBox }, data(){ return{ msg:'测试内容' } } } </script>
子组件代码如下:
<template>
<div>
<!-- 子组件接收父传过来的数据,并侦听内容的更改状态 -->
我是子组件: <input type="text" :value="value" @input="changeValue($event.target.value)"/>
</div>
</template>
<script>
export default {
name: "SonBox",
props: {
value: {
required: true,
}
},
methods: {
changeValue(value){
// 子组件通过update:属性名触发父组件中的.sync修饰符
this.$emit('update:value',value)
}
},
};
</script>

浙公网安备 33010602011771号