首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Vue中动态添加一种类型的组件

在Vue中动态添加一种类型的组件
EN

Stack Overflow用户
提问于 2021-05-21 14:48:19
回答 1查看 47关注 0票数 0

我在"How to dynamically adding different components in Vue"上读到一篇文章。

有一个很好的方法可以将不同的组件绑定到标签上。

但是我想绑定一个类型/名称组件,根据属性的不同而有所不同,而且一个选项卡必须对应于具有相应属性的组件的一个实例。我可以在不同选项卡中重用我的组件吗?

类似于:

代码语言:javascript
复制
<template>
  <button
          v-for="tab in tabs"
          v-bind:key="tab.name"
          v-bind:class="['tab-button', { active: currentTab === tab }]"
          v-on:click="currentTab = tab"
  >
        {{ tab.name }}
  </button>
  <component v-bind:is="currentTab.component" :id_1=currentTab.id_1 :id_2=currentTab.id_2></component>
</template>

<script>
import tab-component from "..."
var tabs = [
  {
    name: "WS1",
    component: "tab-component",
    uwb_id: "PL_DL_test",
    ws_id: "id_Ws_1"
  },
  {
    name: "WS2",
    component: "tab-component",
    uwb_id: "PL_DL_test",
    ws_id: "id_Ws_2"
  }
]

export default {
  components: {
    tab-component
  },
  data() {
    return {
      tabs: tabs,
      currentTab: tabs[0],
    }
  }

}

<script>

有没有可能做这样的事情?

感谢您的回复!

EN

回答 1

Stack Overflow用户

发布于 2021-05-21 15:07:44

为此,您可以使用computed属性。

代码语言:javascript
复制
<template>
  <button
    v-for="(tab, index) in tabs"
    :key="tab.name"
    :class="['tab-button', { active: currentTabIndex === index }]"
    @click="currentTabIndex = index"
  >
    {{ tab.name }}
  </button>
  <component :is="activeTab.component" :prop1="activeTab.prop1 :prop2="activeTab.prop2"></component>
</template>


export default {
  components: {
    tab-component
  },
  data() {
    return {
      tabs: [
        {
          name: "WS1",
          component: "tab-component",
          uwb_id: "PL_DL_test",
          ws_id: "id_Ws_1"
        },
        {
          name: "WS2",
          component: "tab-component",
          uwb_id: "PL_DL_test",
          ws_id: "id_Ws_2"
        }
      ],
      currentTabIndex: 1
    }
  },
  computed: {
    activeTab () {
      return this.tabs[this.currentTabIndex]
    }
  }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67632031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档