.sync **修饰符使用场景
父组件向子组件传值,同时子组件触发方法,需要修改父组件传递过来的数据,这个时候我们可以使用.sync
1 在父组件的子组件标签上添加数据
<子组件标签 v-bind:数据名.sync=”父组件的数据”></子组件标签>
2 在子组件中定义props来接受父组件传递过来的数据
props: {
数据名: {
type: 类型
}
}
3 在子组件触发的事件中,通过this.$emit触发事件,里边的第一个参数应该写为 update:数据名**
子组件触发方法名() {
this.$emit(‘update:数据名’,要传递的数据)
}
<div id="app">
<child :txt.sync="msg" ></child>
</div>
<script>
Vue.component('child', {
props: {
txt: {
type: Number
}
},
template: `
<div class="child">
<button @click="change">修改</button>
{{txt}}
</div>
`,
methods: {
change() {
this.$emit('update:txt',678)
}
}
})
const app=new Vue({
el: '#app',
data: {
msg: 1111
}
})
</script>