sync修饰符是Vue.js中的一个语法糖,它可以实现子组件与父组件的双向绑定,并且可以实现子组件同步修改父组件的值。在Vue.js 2.0版本中,sync修饰符被移除了,但是在实际应用中,我们发现sync还是有其适用之处,比如在开发可复用的组件库时。
使用sync修饰符时,我们需要在子组件中定义一个prop,然后在父组件中使用v-bind指令将这个prop与子组件中的值进行绑定。同时,我们还需要在这个prop前面加上.sync修饰符。这样,当我们在子组件中修改这个prop的值时,父组件中对应的值也会随之更新。
通常我们在子组件中要更改父组件传递的数据,利用$emit方法触发父组件中的方法,通知父组件更改,今天呢我们就通过sync修饰符在子组件中修改父组件中的数据,下面举例说明一下,如有不对的地方还请大家指正。
父组件向子组件传递的数据是100,如果通过子组件直接更改的话,数据是可以更改的,但是控制台的是会报错的;
<template>
<div class="about">
<h2>父组件传递的数据:{{ num }}</h2>
<button @click="update">更改父组件中的数据</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: ['num'],
methods: {
update() {
this.num = 999;
}
},
};
</script>
这个时候我们就可以通过,sync修饰符进行子组件修改父组件中的数据;
//子组件
<template>
<div class="about">
<h2>父组件传递的数据:{{ num }}</h2>
<button @click="update">更改父组件中的数据</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: ['num'],
methods: {
update() {
this.$emit('update:num', 999);
}
},
};
</script>
//父组件
<template>
<div class="about">
<h1>父组件</h1>
<input type="text" v-model="num">
<h1>子组件</h1>
<Sub :num.sync="num" />
</div>
</template>
<script>
import Sub from './sub.vue';
export default {
data() {
return {
num: 100
};
},
components: {
Sub
},
};
</script>
子组件中通过this.$emit('update:num', 999);进行修改父组件中的数据,update:是固定写法,num,则是子组件上的自定义属性,同时在父组件中的子组件标签上,给自定义属性添加.sync即可 <Sub :num.sync="num" />,最后可以看到父组件中的数据也进行了更改,控制台没有报错;