我不知道如何在 Vue Js 中為可重複使用元件建立可變更的文本
P粉957723124
P粉957723124 2023-09-03 22:33:40
0
1
472
<p>我正在透過觀看教學創建一個可重複使用的選項卡元件。看完之後,我明白了它是如何運作的。但是,對於我的項目,我需要建立標題包含可以更改的標題的選項卡,因為這是一個可重複使用的元件,所以我必須更改每個新選項卡的每個標題的標題,但我還沒有弄清楚如何做吧。我需要以某種方式從我添加到頁面的元件 TabsWrapper 取得標題</p> <pre class="brush:php;toolbar:false;"><div class="tab_header">{{title}}</div></pre> <p>然後讓此標題更改此 div 內的文本,該 div 是 TabsWrapper 元件的主標頭。 </p> <pre class="brush:php;toolbar:false;"><div class="tab_header">{{title}}</div></pre> <p>我的程式碼: 第一個是我加入到網站主頁的元件外程式碼。 </p> <pre class="brush:php;toolbar:false;"><TabsWrapper> <Tab title="Tab 1">Hello 1</Tab> <Tab title="Tab 2">Hello 2 </Tab> <Tab title="Tab 3">Hello 3</Tab> <Tab title="Tab 4">Hello 4</Tab> </TabsWrapper></pre> <p>第二個是負責TabsWrapper的元件內部的程式碼</p> <pre class="brush:php;toolbar:false;"><template> <div class="tabs"> <div class="tab_header"></div> <ul class="tabs_header"> <li v-for="title in tabTitles" :key="title" @click="selectedTitle = title" :class=" {selected: title ==selectedTitle}" > {{ title }} </li> </ul> <slot /> </div> </template> <script> import { ref} 從 'vue'; import { provide } from 'vue'; export default{ setup(props,{slots}){ const tabTitles=ref(slots.default().map((tab)=> tab.props.title)) const selectedTitle=ref(tabTitles.value[0]) provide("selectedTitle", selectedTitle) return{ selectedTitle, tabTitles, } } } </script></pre> <p>這段程式碼從 Tab 中取得每個標題</p> <pre class="brush:php;toolbar:false;"><Tab title="Tab 1">Hello 1</Tab></pre> <p>這段程式碼呈現</p> <pre class="brush:php;toolbar:false;"><li v-for="title in tabTitles" :key="title" @click="selectedTitle = title" :class=" {selected: title ==selectedTitle}" > {{ title }} </li></pre> <p>我嘗試重複相同的技術,但它成功了,但我認為還有更好的方法</p> <p> <pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="tabs"> <div class="tab_header" v-for="headtitle in headTitles" :key="headtitle">{{headtitle}}</div> <ul class="tabs_header"> <li v-for="title in tabTitles" :key="title" @click="selectedTitle = title" :class=" {selected: title ==selectedTitle}" > {{ title }} </li> </ul> <slot /> </div> </template> <script> import { ref} 從 'vue'; import { provide } from 'vue'; export default{ setup(props,{slots}){ const tabTitles=ref(slots.default().map((tab)=> tab.props.title)) const headTitles=ref(slots.default().map((tab)=>tab.props.headtitle)) const selectedTitle=ref(tabTitles.value[0]) provide("selectedTitle", selectedTitle) return{ selectedTitle, tabTitles, headTitles, } } } </script></code></pre> </p>
P粉957723124
P粉957723124

全部回覆(1)
P粉418351692

您可以簡單地在腳本標籤中傳遞道具,並使用此關鍵字和道具名稱直接存取它們。

export default {
  props: ['foo'],
  created() {
    // props are exposed on `this`
    console.log(this.foo)
  }
}

在這樣的模板標籤中

<span>{{ foo }}</span>

您不需要使用 ref 您可以直接使用 v-for 並循環遍歷陣列元素。

<li v-for="(item, index) in foo">
  {{item}}
</li>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!