[vue]實現父子組件數據雙向綁定
阿新 • • 發佈:2018-07-29
method 雙向綁定 blog new www. input one res 監聽
參考: http://www.cnblogs.com/xxcanghai/p/6124699.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <switchbtn :result="result" @on-result-change="onResultChange"></switchbtn> <input type="button" value="change" @click="change"> </div> <script src="node_modules/vue/dist/vue.js"></script> <script> Vue.component("switchbtn", { template: "<div @click='change'>{{myResult?'開':'關'}}</div>", props: ["result"], data: function () { return { myResult: this.result//①創建props屬性result的副本--myResult }; }, watch: { result(val) { this.myResult = val;//②監聽外部對props屬性result的變更,並同步到組件內的data屬性myResult中 }, myResult(val) { //xxcanghai 小小滄海 博客園 this.$emit("on-result-change", val);//③組件內對myResult變更後向外部發送事件通知 } }, methods: { change() { this.myResult = !this.myResult; } } }); new Vue({ el: "#app", data: { result: true }, methods: { change() { this.result = !this.result; }, onResultChange(val) { this.result = val;//④外層調用組件方註冊變更方法,將組件內的數據變更,同步到組件外的數據狀態中 } } }); </script> </body> </html>
[vue]實現父子組件數據雙向綁定