Vue:组件之间相互访问

父组件访问子组件有两种方式:

  • 使用$children:得到一个子组件数组
  • 使用refs:得到一个对象

子组件访问父组件:

  • 使用$parent获取父组件

访问根组件:

  • 使用$root
1
2
3
4
this.$children[0]  // 访问第一个子组件
this.$refs.某个子组件的ref值 // 访问定义了ref值的子组件对象
this.$parent.父组件的某个data属性 // 访问父组件的某个data属性
this.$root // 获取根组件

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 父组件 -->
<div id="app">
<button @click="buttonClick">点击我获取子组件</button>
<!-- 调用子组件 -->
<cpn></cpn>
<!-- 定义子组件的引用 -->
<cpn ref="info"></cpn>
</div>

<!-- 子组件模板 -->
<template id='child'>
<div>
<p>这是一个子组件</p>
</div>
</template>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<script>
const app = new Vue({
el:"#app",
methods: {
buttonClick() {
// 获取子组件:使用 $children 或 $refs
// console.log(this.$children[0].message);
console.log(this.$refs.info.message);
}
},
components: {
cpn: {
template: "#child",
data() {
return {
message: "你说啥"
}
},
props: {
title: "this is a props title"
}
}
}
})
</script>