Vue.js組件之同級之間的通訊

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>componentKnowledge-同級組件通訊</title>
    <script src="js/vue.js"></script>
  </head>
  <body>html


  <template id="aa">
    <div>
      I am aa component:{{msg}}
      <input type="button" @click="send" value="SendTo-cc">
    </div>
  </template>vue


  <template id="bb">
    <div>
      I am bb component:{{msg}}
      <input type="button" @click="send" value="SendTo-cc">
    </div>
  </template>app


  <template id="cc">
    <div>
      <div>
      I am cc component:{{msg}}/receive data:{{msg2}},{{msg3}}
      </div>
    </div>
  </template>

  <script>
  window.onload=function(){
    let Event=new Vue();函數

    let aa={//定義組件
      template:'#aa',
      data(){
        return {msg:'aa data'}
      },
      methods:{
        send(){
          Event.$emit('a-send',this.msg)
        }
      }
    };

    let bb={//定義組件
      template:'#bb',
      data(){
        return {msg:'bb data'}
      },
      methods:{
        send(){
        Event.$emit('b-send',this.msg)
        }
      }
    };this


    let cc={//定義組件
      template:'#cc',
      data(){
        return {
          msg:'cc data',
          msg2:'',
          msg3:''
        }
      },
      mounted(){
        Event.$on('a-send',(data)=>{this.msg2=data});
        Event.$on('b-send',(data)=>{this.msg3=data});
      }
    };component

    let vm=new Vue({
      el:'#app',
      components:{//註冊組件
        aa,
        bb,
        cc
      }
    });
  }
    /*同級組件之間的通訊關鍵總結:
      1:新建一個空的root組件:let Event=new Vue();
        其上有兩個方法Event.$emit('a-fnName',data)/Event.$on('a-fnName',(data)=>{})
      2:發送數據的組件:Event.$emit('a-fnName',data)寫在組件的methods裏,
      3:接收數據的組件:Event.$on('a-fnName',(data)=>{}),注意函數格式必須寫爲箭頭函數,否則this指向不是當前組件,通常寫在鉤子函數裏(beforeCreate(){}/created(){}/beforeMount(){}/Mounted(){}/beforeUpdate(){}/updated(){}/beforeDestroy(){}/destroyed(){})htm

    */
  </script>
    <div id="app">ip

      <!--使用組件-->
      <aa></aa>
      <bb></bb>
      <cc></cc>
    </div>
  </body>
</html>input

相關文章
相關標籤/搜索