provide和inject使用场景也是组件传值,尤其是祖父组件--孙组件等有跨度的组件间传值,单向传值(由provide的组件传递给inject的组件)。
provide
选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的属性。
inject
通常是一个字符串数组。
示例:
(1)祖父组件grandpaDom.vue:
<template>
<div>
<father-dom>
</father-dom>
</div>
</template>
<script>
import fatherDom from "./fatherDom.vue";
export default {
provide: {
fooNew: "bar"
},
data() {
return {};
},
components: { fatherDom },
methods: {}
};
</script>
(2)父亲组件fatherDom.vue:
<template>
<div>
<child-dom></child-dom>
</div>
</template>
<script>
import childDom from "./childDom.vue";
export default {
name: "father-dom",
components: { childDom }
};
</script>
(3)孙组件childDom.vue
<template>
<div>
<p>fooNew:{{fooNew}}</p>
</div>
</template>
<script>
export default {
name: "childDom",
inject: ["fooNew"],
methods: {}
};
</script>
效果: