vue3 跨级传递数据

假设我们我们有3层组件 顶层,中间层,底层

如果我们的顶层想给底层传递数据

常规的我们可以用父传子的方式props,顶层传递给中间层,中间层再传给底层,如果中间有很多层,那不炸杠了吗

所以接下来要用vue3推出的provide和inject函数

我们在顶层用provide函数

html 复制代码
<script setup>
import CenterApp from '@/components/center-app.vue';
import {provide} from 'vue'
import {ref} from 'vue'

const count=ref(0)
provide('car','宝马')
provide('count',count)
provide('addcount',()=>{
  count.value++;
})
</script>

<template>
    <div>
        <h1>我是顶部组件</h1>
        <CenterApp></CenterApp>
    </div>
</template>

底层用inject函数来接收,可以接收常量,响应式变量,函数

html 复制代码
<script setup>
import {inject} from 'vue'
const car=inject('car')
const count=inject('count')
const addcount=inject('addcount')
</script>

<template>
    <div>
        <h3 >我是底部组件-----{{car}}-----{{count}}辆</h3>
        <button @click='addcount'>增加</button>
    </div>
</template>
相关推荐
echome88818 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌18 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易18 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常19 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师19 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么19 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒19 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_07619 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端
枣把儿20 小时前
开源!公众号排版+一键发布工具懒人版
前端
2501_9160074720 小时前
抓包工具功能对比,TraceEagle、Charles、Fiddler、Wireshark、mitmproxy 差别
前端·网络协议·ios·adb·https·fiddler·wireshark