Vue组合式API---provide和inject跨层传递函数示例

通过provide和inject除了可以跨层传递数据以外,也可以跨层传递函数,即在顶层组件中定义函数,负责修改顶层组件的数据,这个函数可以传递给底层组件,在底层组件中调用顶层组件的函数。

App.vue文件:

<script setup>
import RoomPage from './components/provide/room-page.vue'

</script>

<template>
  <div>
    <RoomPage></RoomPage>
  </div>
</template>

<style scoped></style>

顶层组件room-page.vue:

<script setup>
import RoomMsgItem from './room-msg-item.vue'
import { provide, ref } from 'vue'

// 组件嵌套关系:
// RoomPage -> RommMsgItem -> RoomMsgComment

// 传递响应式数据
const count = ref(100)
provide('count-key', count)

// 传递方法
const setCount = () => {
    count.value++
}
provide('setCount-key', setCount)
</script>

<template>
    <div class="page">
        顶层组件
        <RoomMsgItem></RoomMsgItem>
    </div>
</template>

<style scoped></style>

中间组件room-msg-item.vue:

<script setup>
import RoomMsgComment from './room-msg-comment.vue'
</script>

<template>
    <div>
        中间组件
        <RoomMsgComment></RoomMsgComment>
    </div>
</template>

<style scoped></style>

底层组件room-msg-comment.vue:

<script setup>
import { inject } from 'vue'

// 接收响应式数据
const countData = inject('count-key')

// 接收方法
const setCount = inject('setCount-key')
</script>

<template>
    <div class="comment">
        底层组件
        <div>
            来自顶层组件的响应式数据---{{ countData }}
        </div>
        <div>
            <button @click="setCount">修改顶层组件的数据</button>
        </div>
    </div>
</template>

<style scoped></style>

到浏览器中查看效果:
在这里插入图片描述

点击按钮:
在这里插入图片描述

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,组合式API可以与v-for指令一起使用,以动态生成组件、列表和其他内容。 首先,我们需要在组件中导入`reactive`和`computed`函数。然后,我们可以使用`reactive`创建一个响应式状态对象,并在`computed`函数中使用它来生成动态内容。最后,我们可以使用v-for指令将内容渲染为列表。 以下是一个使用组合式API和v-for指令的简单示例: ```html <template> <div> <ul> <li v-for="item in items" :key="item.id">{{ item.text }}</li> </ul> </div> </template> <script> import { reactive, computed } from 'vue'; export default { setup() { const state = reactive({ items: [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' }, ], }); const filteredItems = computed(() => { return state.items.filter((item) => { return item.text.includes('2'); }); }); return { items: filteredItems, }; }, }; </script> ``` 在上面的示例中,我们使用`reactive`创建一个响应式状态对象`state`,其中包含一个名为`items`的数组。然后,我们使用`computed`函数创建一个名为`filteredItems`的计算属性,该属性根据特定条件过滤`items`数组中的元素。 最后,我们将`filteredItems`作为组件的输出,然后在模板中使用v-for指令将其渲染为一个列表。在此示例中,我们只渲染了包含数字2的项目。 请注意,由于组合式API使用`setup`函数而不是传统的`data`和`computed`选项,因此我们需要使用不同的语法来定义状态和计算属性。同时,我们也需要使用不同的方式将它们暴露给模板。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值