vue中.sync修饰符有什么用
.sync 修饰符 其实就是一个语法糖
- vue中 :子组件不能修改props 外部数据
- vue中: $emit 可以触发事件并传参
- vue中: $event可以获取 $emit 的参数
好,明白这些之后 场景实现
父组件 parent 有自己的data状态 money 100
父组件中有子组件 child 想把data中的状态给子组件
代码实现
<child :money="money"></child>
// 子组件中有一个button 按钮 每次点击之后 父组件中的data 状态中 money 就要-10 块钱 怎么实现??????
<child :money="money" @handleClick="handleClick"></child>
// 子组件中button 按钮
<button @click="handleClick1"></button>
methods:{
handleClick1(){
this.$emit("handleClick",money - 10)
}
}
// 之后 父组件 再去定义 handleClick方法去接受
// 这种最基本的父子传值方法是不是挺复杂的
下面就是上面代码的优化结果
<child :money="money" ></child>
// 子组件中button 按钮点击事件
<button @click="$emit('updata:money', money - 10)"></button>
// 父组件中
<child :money="money" v-on:updata:money="money = $event"></child>
可以看到上面的方法都是通过监听事件 去通知父组件去修改 子组件不能直接修改
接下来就是 .sync修饰符的作用
<child :money.sync="money"></child>
// 相当于 <child :money="money" v-on:updata:money="money = $event "></child>
// 当然子组件还是要有事件去触发
<button @click="handleClick"></button>
methods:{
handleClick(){
this.$emit("updata:money",money-10)
}
}
大概就是这么多,欢迎补充