子組件修改父組件中的某個屬性值,正常寫法
<body>
<div id="app">
<child :msg="msg" @change="doChange"></child>
</div>
<script src="./js/vue.js"></script>
<script>
// 子組件的配置對象
const child = {
template: `
<div>
<h1>{{msg}}</h1>
<button @click="change">點擊修改h1的內(nèi)容</button>
</div>
`,
props: {
msg: String
},
methods: {
change: function() {
this.$emit("change", "這是被子組件修改后的內(nèi)容");
}
}
};
// 注冊子組件
Vue.component("child", child);
const vm = new Vue({
el: "#app",
data: {
msg: "這是父組件中的數(shù)據(jù)"
},
methods: {
doChange: function(data) {
this.msg = data;
}
}
});
</script>
</body>
使用sync修飾符的寫法
操作步驟:
- 子組件中: this.$emit("update:msg", params); //此處觸發(fā)的事件名稱必須是 "update:變量名"
- 在父組件的組件模板中,找到對應的子組件標簽,把其中的 :msg="msg" 改寫為 :msg.sync="msg"
- 注意: 此處的 "update:msg
<body>
<div id="app">
<child :msg.sync="msg"></child>
</div>
<script src="./js/vue.js"></script>
<script>
// 子組件的配置對象
const child = {
template: `
<div>
<h1>{{msg}}</h1>
<button @click="change">點擊修改h1的內(nèi)容</button>
</div>
`,
props: {
msg: String
},
methods: {
change: function() {
this.$emit("update:msg", "這是被子組件修改后的內(nèi)容");
}
}
};
// 注冊子組件
Vue.component("child", child);
const vm = new Vue({
el: "#app",
data: {
msg: "這是父組件中的數(shù)據(jù)"
}
});
</script>
</body>