Vue 中的.sync修饰符的功能:
当一个子组件改变了一个 prop 的值时,这个变化也会同步到父组件中所绑定。
代码示例:
<Child :money.sync="total"/>
等价于:
<Child :money="total" v-on:updata:money="total=$event"/>
同时子组件要更新money的值时,也需要显式触发一个更新事件:
this.$emit('update:money', newValue)
下面举例说明如何使用:
场景描述:child触发事件向App要钱花。
App.vue:
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
<Child :money.sync="total"/>
/*相当于 <Child :money="total" v-on:updata:money="total=$event"/>*/
</div>
</template>
<script>
import Child from "./Child.vue";
export default {
data() {
return { total: 10000 };
},
components: { Child: Child }
};
</script>
<style>
.app {
border: 3px solid red;
padding: 10px;
}
</style>
child.vue:
<template>
<div class="child">{{money}}
<button @click="$emit('update:money', money-100)">
<span>花钱</span>
</button>
</div>
</template>
<script>
export default {
props: ["money"]
};
</script>
<style>
.child {
border: 3px solid green;
}
</style>
main.js:
// 此处是「非完整版」vue
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
Vue三个规则
- 组件不能修改
props外部数据 this.$emit可以触发事件并传参$event可以获取$emit的参数