2.3.0起.sync修饰符作为一个编译时的语法糖(vue .sync修饰符)
vue修饰符的功能是:当一个子组件改变了一个prop值时,这个变化会同步到父组件所绑定的。
具体实例:
没有使用sync修饰符时,
当子组件需要更新 money 的值时,它需要显式地触发一个更新事件:
this.$emit("update:money", this.money - 10);
然后父组件
<my-comp :money="all" @update:money="all = $event" />
使用sync,
<my-comp :money.sync="all" />
具体代码
<template>
<div>
father money: {{ all }}
<hr />
<!-- <my-comp :money="all" @update:money="all = $event" /> -->
<my-comp :money.sync="all" />
</div>
</template>
<script>
import Vue from "vue";
Vue.component("my-comp", {
template: `<div>child money {{money}}
<button @click="useMoney">花钱</button>
</div>`,
data: function () {
return {
copyFoo: this.foo,
};
},
props: ["money"],
methods: {
useMoney() {
console.log("花钱");
this.$emit("update:money", this.money - 10);
},
},
});
export default {
data() {
return {
all: 100,
};
},
};
</script>