vue父子组件之间数据的双向绑定

2017-05-23  本文已影响365人  JustFantasy
<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//①创建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;//④外层调用组件方注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
        }
    }
});

这个代码我觉得表现得很清楚了,下面的参考地址是原理的详细介绍。
如何在Vue2中实现组件props双向绑定

上一篇 下一篇

猜你喜欢

热点阅读