【问题标题】:Dynamically adding one type of components in Vue在 Vue 中动态添加一种类型的组件
【发布时间】:2021-08-10 09:29:26
【问题描述】:

我读了一篇文章 "How to dynamically adding different components in Vue".

有一种很好的方法可以将不同的组件绑定到选项卡。

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

类似:

<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>

有可能做这样的事情吗?

感谢回答!!!

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您可以为此使用computed 属性。

    <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]
        }
      }
    
    }
    

    【讨论】:

    • 感谢您的回答,但是如何使用这种方法动态传递道具?
    • 此外,在我更改选项卡后,我的 vue 组件的新实例未创建,currentTabIndex 更改,但没有任何反应
    • 我已经更新了我的答案,所以你可以看到传递道具的方式。新标签没有呈现,因为你没有传递任何道具,我想。
    • 我实现了你对我的代码的更新,但无论如何,默认情况下只有一个选项卡组件实例是使用 currentTabIndex 的道具创建的,所以你的答案不起作用。也许我应该将 v-for 与 v-show="visible" 指令一起使用并更新可见属性 onClick 选项卡
    猜你喜欢
    • 1970-01-01
    • 2018-07-02
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2020-12-03
    • 2022-09-30
    相关资源
    最近更新 更多