[vue]实现父子组件数据双向绑定

参考: 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>

转载于:https://www.cnblogs.com/iiiiiher/p/9383781.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值