vue3 跨级传递数据
假设我们我们有3层组件 顶层,中间层,底层https://i-blog.csdnimg.cn/direct/c400489efa494a6fb7599b37442a721b.png
如果我们的顶层想给底层传递数据
通例的我们可以用父传子的方式props,顶层传递给中间层,中间层再传给底层,如果中间有很多层,那不炸杠了吗
所以接下来要用vue3推出的provide和inject函数
我们在顶层用provide函数
<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函数来吸取,可以吸取常量,相应式变量,函数
<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>
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]