Vue3 跨组件传参 provide 与 inject

简介: Vue3 跨组件传参 provide 与 inject

provide 用于:让父组件 传递数据。

inject 用于:让后代组件 接收数据。

语法格式:

// 传递数据
import { provide } from 'vue';
provide('数据名', 数据);
 
// 接收数据
import { inject } from 'vue';
let 变量 = inject('数据名');

跨组件传参:

第一层组件:传递数据。

<template>
  <h3>我是第一层组件</h3>
  <p>{{ info.name }} : {{ info.age }}</p>
  <hr />
  <Two></Two>
</template>
 
<script setup>
// 引用 provide 函数
import { provide, reactive } from 'vue'
import Two from "../components/Two.vue"
let info = reactive({ name: "张三", age: 18 });
// 给后代组件传递数据
provide('info', info);
</script>

第二层组件:接收数据

<template>
  <h3>我是第二层组件</h3>
  <p>{{ info.name }} : {{ info.age }}</p>
  <hr />
  <Three></Three>
</template>
 
<script setup>
// 引用 inject 函数
import { inject } from 'vue'
import Three from "../components/Three.vue"
// 接收数据
let info = inject('info');
</script>

第三层组件:接收数据。

<template>
  <h3>我是第三层组件</h3>
  <p>{{ info.name }} : {{ info.age }}</p>
</template>
 
<script setup>
// 引用 inject 函数
import { inject } from 'vue'
// 接收数据
let info = inject('info');
</script>

最终效果:

:传递的数据可以在任意一层后代组件中使用。


相关文章
|
1天前
|
JavaScript 定位技术 API
在 vue3 中使用高德地图
在 vue3 中使用高德地图
8 0
|
1天前
vue3 键盘事件 回车发送消息,ctrl+回车 内容换行
const textarea = textInput.value.textarea; //获取输入框元素
9 3
|
4天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
14 0
|
4天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
4天前
|
JavaScript 前端开发 安全
Vue3官方文档速通(下)
Vue3官方文档速通(下)
15 0
|
4天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
20 0
|
4天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
26 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
10 0
|
4天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
8 0