问题
在vue中组件之间的互相调用是很频繁的;而且组件与组件之间的关系也有很多种,本篇文章只讨论父组件与子组件之间的关系。分两种情况,一种是父组件调用子组件的数据和方法,另一种就是子组件主动调用父组件的数据和方法。
<template>
<div class="app-header">
</div>
</template>
export default {
components: {},
data() {
return {
test:'hello world'
};
},
methods: {
hello(){
console.log("我是子组件中的--hello world")
}
},
};
这个组件中定义了一个test属性和一个hello方法,我们要在父组件中获取test数据和调用hello方法。
父组件
<template>
<div class="">
<button>获取子组件data中数据</button>
<button>调用子组件中的方法</button>
<Header ref="header"></Header>
</div>
</template>
import Header from '@/components/Header.vue'
export default {
components: {
Header
},
data() {
return {};
},
methods: {
getChileTest(){
console.log(this.$refs.header.test)
},
getChileHello(){
this.$refs.header.hello()
}
},
};
在父组件中首先要引入子组件,并且在components{}中定义,上面的代码中定义了两个方法,分别是获取子组件的数据和调用子组件中的方法。
父组件调用子组件数据和方法
- this.$refs.header.子组件中属性名
- this.$refs.header.子组件中方法名
通过上面两个 vue语句就可以实现我们的需求了
结果如下

子组件掉调用父组件属性和方法
在父组件中添加一个属性和方法
export default {
components: {
Header
},
data() {
return {
animal:'dog'
};
},
methods: {
getChileTest(){
console.log(this.$refs.header.test)
},
getChileHello(){
this.$refs.header.hello()
},
eat(){
console.log(this.animal+"吃饭!")
}
},
};
修改子组件
<template>
<div class="app-header">
<button @click="getParentAnimal()">获取父组件属性</button>
<button @click="getParentEat()">获取父组件方法</button>
</div>
</template>
export default {
components: {},
data() {
return {
test:'hello world'
};
},
methods: {
hello(){
console.log("我是子组件中的--hello world")
},
getParentAnimal(){
console.log(this.$parent.animal)
},
getParentEat(){
this.$parent.eat()
}
},
};
- this.$parent.父组件中属性
- this.$parent.父组件中方法
结果如下

总结
父组件调用子组件
- this.$refs.header.子组件中属性名
- this.$refs.header.子组件中方法名
子组件调用父组件
- this.$parent.父组件中属性
- this.$parent.父组件中方法