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 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦