【问题标题】:Best way to add components dynamically to a Vue app将组件动态添加到 Vue 应用程序的最佳方法
【发布时间】:2021-03-05 10:40:54
【问题描述】:

向您的 vue 应用动态添加组件的最佳方式是什么?

假设您的应用中有三个不同的组件,并且您希望根据数据的值显示每个组件。

data:() => ({
  tab: 1
})
<custom-component-1></custom-component-1> <!-- Show this if tab is 1 -->
<custom-component-2></custom-component-2> <!-- Show this if tab is 2 -->
<custom-component-3></custom-component-3> <!-- Show this if tab is 3 -->

我将尝试所有可能的方法。

【问题讨论】:

    标签: vue.js vuejs2 vue-component nuxt.js


    【解决方案1】:

    使用v-ifv-show

    第一个也是显而易见的方法是将v-if 添加到您的组件中,如下所示:

    <custom-component-1 v-if="tab === 1"></custom-component-1> <!-- Show this if tab is 1 -->
    <custom-component-2 v-if="tab === 2"></custom-component-2> <!-- Show this if tab is 2 -->
    <custom-component-3 v-if="tab === 3"></custom-component-3> <!-- Show this if tab is 3 -->
    

    如果你愿意,你也可以使用v-show,这取决于你。

    查看v-showv-if 之间的区别。 v-show vs v-if

    这可能是最简单的方法,但不是最有效的。 一旦你的代码开始变得更复杂,这段代码就会成为你的地狱

    使用 Vue 的动态组件

    第二种方法是使用Vue的动态组件Link to documention

    这又是我们使用动态组件的示例:

    computed: {
      component: function () {
       return `custom-component-${this.tab}`;
     }
    },
    
    data:() => ({
      tab: 1
    })
    

    我们只需要传递组件的名称:

    <component is="component"> 
    <!-- instead of -->
    <custom-component-number></custom-component-number>
    
     <component :is="component"> </component>
     <button @click="tab++"></button>
    

    使用computedis 属性,我们可以动态地拥有无限的组件。 这是一种很好的干净方式。您将计算部分从您的标记中取出,并将其放入脚本中以获得更清洁和更高效的代码

    如果您使用这种方法,请确保导入并初始化您想要在页面中使用的组件,或者将它们添加到您的 main.js 中,作为全局组件,如下所示:

    import Vue from "vue";
    import Component1 form "~/components/component1.vue";
    import Component2 form "~/components/component2.vue";
    import Component3 form "~/components/component3.vue";
    
    Vue.component("custom-component-1",Component1);
    Vue.component("custom-component-2",Component2);
    Vue.component("custom-component-3",Component3);
    

    您还可以将组件添加到您的页面:

    import customComponent from "~components/customComponent";
    
    export default {
       components : {
         customComponent: "custom-component"
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-06
      • 2014-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2013-07-13
      • 2010-11-07
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多