<template>
  <div>
    <van-tab v-model="activeTab">
      <van-tab-item v-for="tab in tabs" :key="tab.key">
        {{ tab.title }}
      </van-tab-item>
    </van-tab>
<pre><code>&lt;component :is=&quot;activeComponent&quot; :key=&quot;activeTab&quot;&gt;&lt;/component&gt;
</code></pre>
  </div>
</template>
<script>
export default {
  data() {
    return {
      activeTab: '', // 当前选中的tab页的key属性
      tabs: [
        { key: 'tab1', title: 'Tab 1' },
        { key: 'tab2', title: 'Tab 2' },
        { key: 'tab3', title: 'Tab 3' }
      ]
    };
  },
  computed: {
    activeComponent() {
      // 根据当前选中的tab页的key属性返回对应的组件名
      switch (this.activeTab) {
        case 'tab1':
          return 'Tab1Component';
        case 'tab2':
          return 'Tab2Component';
        case 'tab3':
          return 'Tab3Component';
        default:
          return '';
      }
    }
  }
};
</script>
<p>在上述代码中,<code>activeTab</code>是用来保存当前选中的tab页的key属性的变量。<code>tabs</code>数组定义了每个tab页的key和标题。<code>activeComponent</code>计算属性根据当前选中的tab页的key属性返回对应的组件名。</p>
<p>在模板中,使用<code>van-tab</code>组件来渲染tab页,并使用<code>v-for</code>指令遍历<code>tabs</code>数组。在<code>component</code>标签中使用<code>:is</code>属性来绑定当前选中的组件名,并使用<code>:key</code>属性来确保在切换tab时重新渲染组件。</p>
<p>注意:在使用动态组件时,需要在<code>&lt;template&gt;</code>标签外添加<code>&lt;component&gt;</code>标签。</p>

原文地址: https://www.cveoy.top/t/topic/qpEn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录