为了账号安全,请及时绑定邮箱和手机立即绑定

33.$refs、$parent、$children使用

标签:
JavaScript

1、ref为子组件指定一个索引名称,通过索引来操作子组件;
2、this.$parent 可以直接访问该组件的父实例或组件;
3、父组件也可以通过this.$children 访问它所有的子组件,
$parent和$children 可以递归向上或向下无线访问, 直到根实例或最内层的组件。

案例

index.vue

<template><div>
  <testVue ref="childVue"></testVue>  <br/><br/>
  <testVue2></testVue2> <br/><br/>
  <button @click="clickChild1">点击访问子组件</button> <br/><br/>
  <button @click="clickChild2">点击访问子组件2</button></div></template><script>import testVue from './testVue'import testVue2 from './testVue2'export default {
  data(){    return {      total: 0
    }
  },  methods: {
    clickChild1(){      console.log(this.$refs.childVue.counter);
    },
    clickChild2(){       console.log(this.$children[1].testval);
    }
  },  components: {
    testVue,
    testVue2  
  }
}</script>

test.vue

<template><div>
  <button @click="parentClick">点击访问父组件</button></div></template><script>export default {
  data(){    return {      counter: 0
    }
  },  methods: {
    parentClick(){       console.log(this.$parent.total);
    }
  }
}</script>

test2.vue

<template><div></div></template><script>export default {
  data(){    return {      testval: '2222'
    }
  }
}</script>



作者:圆梦人生
链接:https://www.jianshu.com/p/69563148583d


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消