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>