vue中组件间的传值为单向传递,子组件想要更新父组件的值,需要用emit触发父组件函数,用.sync修饰符简化父组件中监听事件过程。
例如:
// 此处是「非完整版」vue, main.js
import Vue from "vue";
import App from "./App.vue";
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
//此处是 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>
// 此处是 app.vue
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
<Child :money="total" v-on:update: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>
通过.sync 语法糖 可以改写以上代码,:money.sync="total"等价于:money="total" v-on:update:money="total=$event"
例如:
<template>
<div class="app">
App.vue 我现在有 {{total}}
<hr>
<Child :money.sync="total"/>
</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>