provide/inject
使用方式
- 祖先组件里提供 provide
- 子孙
- 组件里,inject 相应的名字即可
// Parent.vue <template> <div class="container"> <h3>provide/inject 传递方法</h3> <div class="description"> 在父组件中通过 provide 向子孙组件提供方法,在子孙组件中通过 inject 获取父组件提供的方法 </div> <br /> <Child></Child> </div> </template> <script> import Child from "./Children"; export default { name: "Father", components: { Child, }, provide() { return { fatherMethod: this.fatherMethodHandle, }; }, methods: { fatherMethodHandle() { console.log("我是父组件的方法"); }, }, }; </script> <style scoped lang="scss"> </style>
子组件
// Child.vue
<template>
<div>
<button @click="childMethod">我是子组件</button>
</div>
</template>
<script>
export default {
name: "Child",
props: {
msg: String,
},
inject: ["fatherMethod"],
methods: {
childMethod() {
console.log("我是子组件的方法,我在子组件中调用了父组件的方法");
this.fatherMethod();
},
},
};
</script>
<style scoped lang="scss">
</style>
一个子组件可以会在多个父组件中使用,当某一个父组件不存在时,此时inject会中的方法会报错,给inject默认值即可
// 转为这种写法
inject: {
getTable: { value: "getTable", default: null },
}