provide和inject使用场景也是组件传值,尤其是祖父组件--孙组件等有跨度的组件间传值,记住是单向的。孙组件不能向祖父组件传值。
provide
选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的属性。
inject
通常是一个字符串数组。
示例:
(1)祖父组件grandpaDom.vue:
<template> <div> <father-dom :fooNew=‘fooNew‘> </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>
效果:
原文地址:https://www.cnblogs.com/mengfangui/p/9995957.html
时间: 2024-10-09 03:35:53