组件通信之 inject & $parent
provide & inject 用法
多级子组件中修改主页面数据时,需要调用主页面的方法刷新页面时使用
注意事项:
1、provide 和 inject 方法只能在父子组件间进行数据的传递和共享,兄弟组件之间无法使用
2、provide 和 inject 不是响应式的,也不会对数据进行监听给,如果需要在子组件中监听父组件提供的数据的变化,建议使用计算属性或者watch方法
3、provide和inject方法不会对注入的数据进行类型检查和默认值设定
4、provide和inject方法只有在组件初始化时才会进行数据的提供和注入,组件初始化后再进行数据提供和注入可能导致错误
1. 父组件
<template>
<div>
<h2>父组件</h2>
<p>Message: {{ message }}</p>
<ChildComponent />
</div>
</template>
<script>
import ChildComponent from './ChildComponent'
export default {
components: {
ChildComponent
},
data() {
return {
tableData: [],
tableHeight: 0,
}
},
provide() {
return {
message: "hello word", // 传递数据
refresh : this.query(), // 调用 query 方法刷新主页面
... //可定义多个方法
}
},
methods: {
}
}
</script>
2. 子组件调用
<template>
<div>
<h2>子组件</h2>
<p>Message: {{ message }}</p>
</div>
</template>
inject: ['refresh', 'message'],
methods: {
hanldeFunc(){
this.refresh()
}
}
$parent & $childre 用法
1、组件
注意事项:
1、子实例可以用 this.$parent 访问父实例,子实例被推入父实例的 $children 数组中
2、当前组件没有父组件时, $parent 为 undefined
3、父组件可以有多个子组件,如果一个组件有多个父组件,但是 $parent 只能有一个值,使用时需注意
父组件
<template>
<div style="background-color: #999">
<h2>父组件</h2>
<children1 ref="children1" :data1="data1" />
<children2 ref="children2" :data2="data2" />
</div>
</template>
<script>
import children1 from "./children1 .vue"
import children2 from "./children2 .vue"
export default {
props: ["data1"],
data() {
return {
data1: 'data1',
data2: "data2",
};
},
methods: {
methods1(arg1) {
console.log(111, arg1)
},
},
};
</script>
<style>
</style>
子组件1
<template>
<div style="background-color: #999">
<h2>子组件1</h2>
<el-button @click="clickEvent">点击</el-button>
</div>
</template>
<script>
export default {
data() {
return {
sonData1: 'sonData1',
};
},
methods: {
sonMethods1(arg1) {
console.log(111, arg1)
},
clickEvent(){
// 传值给父组件
this.$parent.data1 = this.sonData1
// 调用父组件方法
this.$parent.methods1(this.sonData1)
}
},
};
</script>
<style>
</style>
子组件2
<template>
<div style="background-color: #999">
<h2>子组件2</h2>
<el-button @click="clickEvent">点击</el-button>
</div>
</template>
<script>export default {
data() {
return {
sonData2: 'sonData2',
};
},
methods: {
sonMethods2(arg1) {
console.log(111, arg1)
},
clickEvent(){
// 传值给父组件
this.$parent.data2 = this.sonData2
// 调用兄弟组件的方法
this.$paren.$refs['children2'].sonMethods1(this.sonData2)
}
},
};
</script>
<style>
</style>