Vue.js父子通訊之全部方法和數據共享

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>parentChildComponent</title>
    <script src="js/vue.js"></script>html

    <template id="parent">
      <div>
        I am parent component !{{msg}};I accept :{{msg2}}
        <hr>
        <child ref="child"></child>
      </div>
    </template>vue

    <template id="child">
      <div>
        I am child component !{{msg}};I accept :{{msg2}}
      </div>
    </template>app

  </head>
  <body>
  <script>
    window.onload=function(){
      let child={
        template:'#child',
        data(){
          return {
            msg:'Data of child !',
            msg2:''
          }
        },
        mounted(){
          this.msg2=this.$parent.msg;
        }
      };
      let parent={
        template:'#parent',
        components:{
            child
        },
        data(){
          return {
            msg:'Data of parent !',
            msg2:''
          }
        },
        mounted(){
          this.msg2=this.$refs.child.msg
        }
      };
      new Vue({
        el:'#app',
        components:{
            parent
        }
      });
    }
</script>
    <div id="app">
      <parent></parent>
    </div>
</body>
</html>this

    打通父子之間全部數據和方法的共享:
      父模板:<child ref="子名稱"></child>
      父訪問子: 父組件: this.$refs.子名稱.子數據/方法名()
      子訪問父: 子組件: this.$parent.子數據/方法名()component

相關文章
相關標籤/搜索