父子組件訪問
有時候我們需要父組件直接訪問子組件、子組件直接訪問父組件
父組件訪問子組件
父組件訪問子組件有兩種方式,第一種方式是使用 $children,第二種方式是使用 $refs
使用$children(不常使用)
使用 $children 是拿到所有的子組件
使用 $children訪問:this.$children是一個數組類型,它包含所有子組件對象
$children使用方法
注意事項:
(1)使用 this.$children得到的是一個擁有所有子組件的數組類型
(2)單個子組件時可以調用子組件的數據、方法等等
(3)重要部分標有註釋
<body>
//<!-- 父組件模板 -->
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
<button @click="btn">點我</button>
</div>
//<!-- 子組件模板 -->
<template id="cpn">
<div>
<h2>我是子組件</h2>
</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:"hello vue"
},
methods:{
//使用方法:
btn() {
console.log( this.$children);
for(let child of this.$children){
console.log(child.message);
child.show();
}
}
},
//子組件
components:{
cpn:{
template:"#cpn",
data() {
return {
message:"我是子組件的message"
}
},
methods:{
show() {
console.log("show");
}
}
}
}
})
</script>
</body>
使用$refs(經常使用)
使用 $refs拿到某一個子組件
$refs使用方法
注意事項:
(1)$refs 是一個對象類型,組件中沒有ref屬性時默認是一個空的對象
(2)以下代碼於上部分代碼大部分相同,這裏只展示修改部分
//<!-- 父組件模板 -->
<div id="app">
<cpn></cpn>
<cpn></cpn>
//更改
<cpn ref="a"></cpn>
<button @click="btn">點我</button>
</div>
methods:{
btn() {
//更改
console.log(this.$refs);
console.log(this.$refs.a);
console.log(this.$refs.a.message);
}
},
子組件訪問父組件和根組件(使用較少)
子組件訪問父組件使用 $parent,訪問根組件使用 $root
主要看Javascript部分代碼,以註釋標記處爲重點
<body>
//<!-- 父組件模板 -->
<div id="app">
<cpn></cpn>
</div>
//<!-- 子組件模板 -->
<template id="cpn">
<div>
<h2>我是子組件</h2>
<button @click="btn">點我</button>
</div>
</template>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el:'#app',
data:{
message:"我是Vue實例"
},
components:{
cpn:{
template:"#cpn",
methods:{
btn() {
//訪問父組件
console.log(this.$parent);
console.log(this.$parent.message);
//訪問根組件
console.log("我是根組件");
console.log(this.$root);
}
}
}
}
})
</script>
</body>