Vue2.x之非父子组件传值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>给组件绑定原生事件</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <child ref="one" content="Quincy"></child>
    <child ref="two" content="Cui"></child>
  </div>
  <script>
    Vue.prototype.bus = new Vue();
    Vue.component('child',{
      props:{
        content:{
          type:String
        }
      },
      data:function () {
        return {
          selfContent:this.content
        }
      },
      template:'<div @click="handleClick">{{content}}</div>',
      methods:{
        handleClick(){
          this.bus.$emit('change',this.selfContent)
        }
      },
      mounted:function(){
        let this_ = this;
        this.bus.$on('change',function (value) {
          this_.content = value
        })
      }
    });
    let app = new Vue({
      el:'#app',

    })
  </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_33733970/article/details/81278782