Vue.js父子通信之所有方法和数据共享


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

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

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

  </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>

    打通父子之间所有数据和方法的共享:
      父模板:<child ref="子名称"></child>
      父访问子: 父组件: this.$refs.子名称.子数据/方法名()
      子访问父: 子组件: this.$parent.子数据/方法名()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM