vue2 双向绑定

  代码出处https://juejin.im/entry/5843abb1a22b9d007a97854c

  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <!--开关组件--> 
        <switchbtn :result="result" on-result-change="onResultChange" ></switchbtn>
        <!--外部控制-->
        <input type="button" value="change" @click="change">
    </div>

    <script src="https://vuejs.org/js/vue.js"></script>
    <script>
        //开关组件代码
        Vue.component("switchbtn",{
            template:"<div @click='change'>{{myresult ? '开':'关'}}</div>",
            props:["result"],
            data:function() {
                return {
                    myresult : this.result
                }
            },
            methods:{
                change(){
                    this.myresult=!this.myresult;
                }
            },
            watch: {
                result(val) {
                    this.myresult = val;//新增result的watch,监听变更并同步到myResult上
                },
                myresult(val){
                    //xxcanghai 小小沧海 博客园
                    this.$emit("on-result-change",val);//③组件内对myResult变更后向外部发送事件通知
                }
            },
        });

        //调用组件
        new Vue({
            el: "#app",
            data:{
                result:true//开关状态数据
            },
            methods:{
                change(){
                    this.result=!this.result;
                },
                onResultChange(val){
                    this.result=val;//④外层调用组件方注册变更方法,将组件内的数据变更,同步到组件外的数据状态中
                }
            }
        });
    </script>    
</body>
</html>
原文地址:https://www.cnblogs.com/a-flydog/p/6872651.html