所以我正在嘗試使用 Vue 3 和插槽創建一個動態選項卡選單。我讓標簽正常作業,我有 BaseTabsWrapper 和 BaseTab 組件。我需要能夠在 BaseTabsWrapper 組件內使用 BaseTab 組件進行 v-for。像這樣:
<section
id="content"
class="w-full mx-2 pr-2"
v-if="incomingChatSessions && incomingChatSessions.length"
>
<BaseTabsWrapper>
<BaseTab
v-for="chatSession in incomingChatSessions"
:key="chatSession.id"
:title="chatSession.endUser.name"
>
<p>{{ chatSession }}</p>
</BaseTab>
</BaseTabsWrapper>
</section>
我發現的答案中的一個重要警告是,incomingChatSessions 物件是異步的,并且來自 websocket(我已經測驗過這個物件作業正常并且正確地提供所有資料,也就是永遠不是一個空物件)。
BaseTabsWrapper 模板內部。重要部分:
<template>
<div>
<ul
class="tag-menu flex space-x-2"
:class="defaultTagMenu ? 'default' : 'historic'"
role="tablist"
aria-label="Tabs Menu"
v-if="tabTitles && tabTitles.length"
>
<li
@click.stop.prevent="selectedTitle = title"
v-for="title in tabTitles"
:key="title"
:title="title"
role="presentation"
:class="{ selected: title === selectedTitle }"
>
<a href="#" role="tab">
{{ title }}
</a>
</li>
</ul>
<slot />
</div>
</template>
和腳本:
<script>
import { ref, useSlots, provide } from 'vue'
export default {
props: {
defaultTagMenu: {
type: Boolean,
default: true,
},
},
setup(props) {
const slots = useSlots()
const tabTitles = ref(
slots.default()[0].children.map((tab) => tab.props.title)
)
const selectedTitle = ref(tabTitles.value[0])
provide('selectedTitle', selectedTitle)
provide('tabTitles', tabTitles)
return {
tabTitles,
selectedTitle,
}
},
}
</script>
這是 Tab 組件模板:
<template>
<div v-show="title === selectedTitle" class="mt-4">
<slot />
</div>
</template>
<script>
import { inject } from 'vue'
export default {
props: {
title: {
type: String,
default: 'Tab Title',
},
},
setup() {
const selectedTitle = inject('selectedTitle')
return {
selectedTitle,
}
},
}
</script>
我的劇本中最重要的部分也是給我帶來很多麻煩的部分是這個:
const tabTitles = ref(
slots.default()[0].children.map((tab) => tab.props.title)
)
我在這里所做的是根據每個插槽的屬性“標題”創建一組選項卡標題,但是當我加載頁面時,即使我從 API 獲取更多標題元素,這個陣列也總是只有一個標題。我注意到的一件事是,如果我從我的代碼中強制重新渲染頁面,那么 tabTitles 陣列的元素數量是正確的,并且我在選單上獲得了正確數量的選項卡。我已經測驗過,我控制來自 websocket 的資料的異步性以隱藏“incomingChatSessions”陣列的方式一切正常,但盡管我嘗試 tabTiles 無論如何總是只得到一個元素。
uj5u.com熱心網友回復:
我會做這樣的事情:
computed(
() => slots.default()[0].children.map((tab) => tab.props.title)
)
它應該在組件更新時更新計算屬性(如插槽更改)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/461452.html
標籤:javascript Vue.js Vuex
下一篇:在函式中呼叫React鉤子
