vue3中的provide 与 inject

编程入门 行业动态 更新时间:2024-10-22 07:56:49

vue3中的<a href=https://www.elefans.com/category/jswz/34/1768964.html style=provide 与 inject"/>

vue3中的provide 与 inject

一、概述

作用:实现祖先与后代组件的通信。一般为祖孙通信,因为子组件可以用props来通信。  

语法:父组件中:provide('car', car)    子组件中:let car = inject('car')

二、举例说明(代码如下)

(1)目录结构 

(2)parentView.vue(provide传递数据)

<template><div class="parent"><h2>父组件:{{ name }}---{{ price }}</h2><Child></Child></div>
</template><script>
import { provide, reactive, toRefs } from 'vue';
import Child from './childView.vue'export default {components: {Child},setup() {let car = reactive({name: '法拉利',price: '20K'})// provide传递数据provide('car', car)return {...toRefs(car)}}
}
</script><style>
.parent {padding: 10px;background-color: skyblue;
}
</style>

(3)childView.vue

<template><div class="child"><h2>子组件:{{ name }}---{{ price }}</h2><Sun></Sun></div>
</template><script>
import Sun from './sunView.vue'
export default {components: {Sun},setup() {}
}
</script><style>
.child {padding: 10px;background-color: skyblue;
}
</style>

(4)sunView.vue(inject接收数据)

<template><div class="sun"><h2>孙组件:{{ car.name }}---{{ car.price }}</h2></div>
</template><script>
import { inject } from 'vue';export default {setup() {// inject 接收数据let car = inject('car')return {car}}
}
</script><style>
.sun {padding: 10px;background-color: pink;
}
</style>

三、最终效果展示

更多推荐

vue3中的provide 与 inject

本文发布于:2023-12-03 17:06:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1656903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:provide   inject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!