Vue 學習筆記 3:前言
相比 1.x,Vue 2 除了引入 Virtual DOM,最讓人一時不習慣的改動就是移除了 props 的雙向綁定。過去用 .sync 或 twoWay 修飾符就能搞定的事,現在必須自己動手。

父元件透過 DOM attribute 把 props 傳進子元件,子元件被動接收,且不該直接改寫外層傳進來的值。官方給的理由是:單向綁定可以避免子元件意外改動父元件狀態,否則資料流會變得難以理解。
這個設計對整體專案是正確的,但實務上確實存在「元件內部需要改 props」的場景。
需求只有兩條:點擊按鈕切換開/關;不點擊時也能由外部資料改變狀態(例如做聯動開關)。

<div id="app"> <switchbtn :result="result"></switchbtn> <input type="button" value="change" @click="change"> </div>
Vue.component("switchbtn", {
template: "<div @click='change'>{{ result ? '開' : '關' }}</div>",
props: ["result"],
methods: {
change() { this.result = !this.result; }
}
});
new Vue({
el: "#app",
data: { result: true },
methods: { change() { this.result = !this.result; } }
});在 Vue 2 執行這段程式碼,點擊開關時會出現警告:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders...
既然 result 不可寫,就在 data 裡開一個 myResult,初始值取自 props,元件內部一律改用這個副本。
Vue.component("switchbtn", {
template: "<div @click='change'>{{ myResult ? '開' : '關' }}</div>",
props: ["result"],
data: function () {
return { myResult: this.result };
},
// ...
});父元件改了 props,子元件對應的 props 會更新,但 data 裡的副本不會自動跟著動,所以要補一個 watch。
watch: {
result(val) {
this.myResult = val; // 外部變更同步到內部副本
}
}內部改了 myResult,外部無從得知,於是再監聽副本,透過 $emit 拋事件,由父元件自己決定要不要同步。
<div id="app"> <switchbtn :result="result" @on-result-change="onResultChange"></switchbtn> <input type="button" value="change" @click="change"> </div>
Vue.component("switchbtn", {
template: "<div @click='change'>{{ myResult ? '開' : '關' }}</div>",
props: ["result"],
data: function () {
return { myResult: this.result }; // ① 建立副本
},
watch: {
result(val) { this.myResult = val; }, // ② 外部 → 內部
myResult(val) {
this.$emit("on-result-change", val); // ③ 內部 → 外部通知
}
},
methods: {
change() { this.myResult = !this.myResult; }
}
});
new Vue({
el: "#app",
data: { result: true },
methods: {
change() { this.result = !this.result; },
onResultChange(val) { this.result = val; } // ④ 父元件決定是否同步
}
});一句話總結:元件內部自己變了要告訴外部,外部決定要不要跟著變。

雙向綁定不利於狀態管理,業務越複雜越應節制,複雜的資料流建議直接上 Vuex。判斷是否真的需要,我會看三個條件:
符合的例子就是這個 switch 開關,或 Tab 元件的 activeIndex——外部需要控制目前開啟哪一頁。
如果有多個 props 都要雙向綁定,照上面的寫法會非常冗餘,所以我寫了一個 mixin 來自動化:
使用方式很簡單,引入 mixin 並宣告即可:
import propsync from './mixins/propsync';
export default {
name: "tab",
mixins: [propsync], // 宣告使用
props: {
active: { type: [String, Number] }, // 自動產生 p_active
width: { type: [Number, String], propsync: false } // 這支不做雙向綁定
},
methods: {
setActive(page, index, e) {
this.p_active = index; // 直接用 p_active
}
}
}命名規則是在 prop 名稱前加上 p_,可在原始碼開頭自行調整。呼叫端只要監聽 onPropsChange 事件,就能拿到「屬性名、新值、舊值」三個參數:
<tab :active="active" @onPropsChange="change"></tab>
change: function (propName, newVal, oldVal) {
this[propName] = newVal;
console.log("元件 tab 的 " + propName + " 屬性變更為 " + newVal);
}原始碼已放在 GitHub:https://github.com/xxcanghai/cnblogsFiles/blob/master/vue-mixins/propsync.js
相關筆記
Vue 學習筆記-1(https://www.jb51.net/article/98869.htm)、Vue 學習筆記-2(https://www.jb51.net/article/98878.htm)、Vue 學習筆記-3(https://www.jb51.net/article/98881.htm)