原因
因為在子組件的過程中,對父組件傳過來的值進行了賦值操作,破壞了vue的單向數(shù)據(jù)流傳遞的,所以報錯
改正方法

image.png
兩種方式
1.用 $emit(‘update:xxx’) 改變。這種方式并沒有改變單向數(shù)據(jù)流的特性
2.將prop定義為對象,改變對象中的值不會觸發(fā)報錯,頁面也能正常渲染、更新。但是如果你對數(shù)據(jù)流不是門清,還是別這么做了。,也就是傳入一個對象,然后改變對象,這樣不會報錯.
props實現(xiàn)雙向數(shù)據(jù)流的一個方式
Vue.component("switchbtn", {
template: "<div @click='change'>{{myResult?'開':'關(guān)'}}</div>",
props: ["result"],
data: function () {
return {
myResult: this.result//①創(chuàng)建props屬性result的副本--myResult
};
},
watch: {
result(val) {
this.myResult = val;//②監(jiān)聽外部對props屬性result的變更,并同步到組件內(nèi)的data屬性myResult中
},
myResult(val){
//xxcanghai 小小滄海 博客園
this.$emit("on-result-change",val);//③組件內(nèi)對myResult變更后向外部發(fā)送事件通知
}
},
methods: {
change() {
this.myResult = !this.myResult;
}
}
});
new Vue({
el: "#app",
data: {
result: true
},
methods: {
change() {
this.result = !this.result;
},
onResultChange(val){
this.result=val;//④外層調(diào)用組件方注冊變更方法,將組件內(nèi)的數(shù)據(jù)變更,同步到組件外的數(shù)據(jù)狀態(tài)中
}
}
});