首页  >  问答  >  正文

我不知道如何在 Vue Js 中为可重用组件创建可更改的文本

<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} from '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} from '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粉957723124P粉957723124411 天前468

全部回复(1)我来回复

  • P粉418351692

    P粉4183516922023-09-04 00:29:55

    您可以简单地在脚本标签中传递道具,并使用此关键字和道具名称直接访问它们。

    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>

    回复
    0
  • 取消回复