Vue3使用插槽時的父子組件傳值
用法見官方檔案深入組件章節,插槽部分:
參考檔案:插槽-作用域插槽-插槽prop
作用域插槽
有時讓插槽內容能夠訪問子組件中才有的資料是很有用的,
需求:插槽內容能夠訪問子組件中才有的資料
實作
子組件
TodoList.vue
<template>
<div v-for="(todoItem, index) in state.todoList">
<slot :item="todoItem" :index="index"></slot>
</div>
</template>
<script setup>
import { reactive } from '@vue/reactivity'
const state = reactive({
todoList: ['Feed a cat', 'Buy milk']
})
</script>
<style lang="less">
</style>
-
在子組件插槽上定義需要傳遞的屬性,如上代碼中的
item和index; -
子組件將子組件中定義的資料通過插槽屬性傳遞給父組件;
父組件
useSlot.vue
<template>
<div>
<todo-list>
<template v-slot:default="slotProps">
<button @click="handleClick(slotProps)">{{slotProps.item}}</button>
</template>
</todo-list>
<div>
<h3>點擊按鈕</h3>
<li>{{`${state.slotProps.index + 1}: ${state.slotProps.item}`}}</li>
</div>
</div>
</template>
<script setup>
import { reactive } from '@vue/reactivity'
import TodoList from './TodoList.vue'
const state = reactive({
slotProps: {
index: 0,
item: 'default'
}
})
const handleClick = (slotProps) => {
state.slotProps = slotProps
}
</script>
<style lang="less">
</style>
-
父組件中定義插槽屬性名字slotProps
默認插槽 <template v-slot:default="slotProps"> ... 當使用具名插槽時 <template v-slot:other="slotProps"> ... -
屬性slotProps獲取子組件傳遞過來的插槽屬性
注意:
- 屬性只能在插槽內部才能獲取
- 具名插槽寫法
演示

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/472930.html
標籤:其他
上一篇:超越聯邦學習,讓AI跨越公司邊界:解決資料隱私和場景模型定制問題
下一篇:保存Outlook電子郵件
