19:vue3 依赖注入

1、通过Prop 逐级透传问题(传统老的方法只能逐级传递)

 传统方式代码如下:

App.vue

 1 <template>
 2   <h3>祖宗</h3>
 3   <Parent :msg="msg"></Parent>
 4 </template>
 5 
 6 <script>
 7 import Parent from "./components/Parent.vue"
 8 export default{
 9     data(){
10       return{
11         msg:"祖宗来的消息"
12       }
13     },
14     
15    components:{
16     Parent
17    }
18 }
19 </script>

Parent.vue

 1 <template>
 2     <h3>Parent</h3>
 3     {{ msg }}
 4 
 5    <Child :msg="msg"></Child>
 6 </template>
 7 
 8 <script>
 9 import Child from './Child.vue';
10 export default{
11     data(){
12       return{
13         
14       }
15     },
16     
17    components:{
18     Child
19    },
20    props:["msg"]
21 }
22 </script>

Child.vue

 1 <template>
 2     <h3>Child</h3>
 3    {{ msg }}
 4 </template>
 5 
 6 <script>
 7 export default{
 8     data(){
 9       return{
10        
11       }
12     },
13     
14    props:["msg"]
15 }
16 </script>

效果截图:

2、使用Provide和inject方式依赖注入实现

通过Prop逐级透传,当层级少还可以用,层级多了就无法使用了。下面使用Provide和inject方式依赖注入实现

 App.vue

 1 <template>
 2   <h3>祖宗</h3>
 3   <Parent></Parent>
 4 </template>
 5 
 6 <script>
 7 import Parent from "./components/Parent.vue"
 8 export default{
 9     data(){
10       return{
11         msg:"祖宗来的消息"
12       }
13     },
14    components:{
15     Parent
16    },
17    provide(){
18     return {
19       message: "祖宗的财产!",
20       msg:this.msg
21     }
22     
23    }
24 }
25 </script>
Parent.vue
 1 <template>
 2     <h3>Parent</h3>
 3    <Child></Child>
 4 </template>
 5 
 6 <script>
 7 import Child from './Child.vue';
 8 export default{
 9     data(){
10       return{
11         
12       }
13     },
14     
15    components:{
16     Child
17    }
18 }
19 </script>
Child.vue
 1 <template>
 2     <h3>Child</h3>
 3    <p>{{ message }}</p>
 4    <P>{{ funMessage }}</P>
 5    <p>{{ msg }}</p>
 6 </template>
 7 
 8 <script>
 9 export default{
10     data(){
11       return{
12         funMessage:this.message
13       }
14     },
15     inject: ["message",'msg']
16 }
17 </script>

效果:

 

--------------

在main.js加入全局

 Child.vue

 

效果:

 提示:

provide和inject只能由上到下的传递,不能反向传递

 

 

 

posted on 2023-07-12 11:33  wuzx-blog  阅读(55)  评论(0编辑  收藏  举报