Vue中父子组件的访问方式

  1. 父访问子:this.$children或this.$refs.ref
  2. 子访问父:this.$parent和this.$root

示例一:

<!-- 父组件 -->
<div id="app">
  <h2>父组件</h2>
  <h2>{{message}}</h2>
  <button @click="btnClick">父组件按钮</button>
  <!-- <cpn :cmessage="message" /> -->
  <cpn ref="aa"></cpn>
  <cpn ref="bb"></cpn>
  <cpn ref="cc"></cpn>
</div>

<!-- 子组件 -->
<template id="cpn">
  <div>
    <h2>子组件</h2>
    <h2>{{cmessage}}</h2>
  </div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
  el:'#app',
  data(){
    return{
      message:'你好,小鱼儿'
    }
  },
  methods:{
    btnClick(){//点击访问子组件对象
      //1.$children
    //  console.log(this.$children);
    //  this.$children[0].showMessage();
    //  console.log(this.$children[0].name);

     //2.$refs=>对象类型,使用更多
     console.log(this.$refs.bb.name);
    }
  },
  //注册组件
  components:{
    cpn:{
      template:'#cpn',
      props:{
        cmessage:String
      },
      data(){
        return{
          name:'子组件name'
        }
      },
      methods:{
        showMessage(){
          console.log("showMessage");
        }
      }
    }
  }
})
</script>

示例二:

<!-- 父组件 -->
<div id="app">
  <cpn></cpn>
</div>
<!-- 子组件 -->
<template id="cpn">
  <div>
    <h2>子组件</h2>
    <button @click="btnClick">子组件按钮</button>
  </div>
</template>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
  el:'#app',
  data(){
    return{
      message:'你好,小鱼儿'
    }
  },
  methods:{
    showMessage(){
      console.log("父组件函数:showMessage()");
    }
  },
  //组件
  components:{
    cpn:{
      template:'#cpn', 
      data(){
        return{
          name:'cpn组件的name'
        }
      },
      methods:{
      btnClick(){
        //1.$parent不建议使用
        // console.log(this.$parent.message);
        // console.log(this.$parent.showMessage())
        
        //2.$root:不管上层有多少父组件,直接定位访问到最上层vue实例:使用较少
        console.log(this.$root);
        console.log(this.$root.message);
      }
    }
    },
   
  }
})
</script>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值