首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向Vue应用程序动态添加组件的最佳方法

向Vue应用程序动态添加组件的最佳方法
EN

Stack Overflow用户
提问于 2020-11-22 15:48:58
回答 1查看 772关注 0票数 0

向vue应用程序动态添加组件的最佳方法是什么?

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

代码语言:javascript
复制
data:() => ({
  tab: 1
})
代码语言:javascript
复制
<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 -->

我要研究所有可能的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-22 15:48:58

使用v-ifv-show

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

代码语言:javascript
复制
<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-显示与v-if

这可能是最简单的方法,但不是最有效的。一旦您的代码变得更加复杂,这段代码将成为您的地狱。

使用Vue的动态组件

第二种方法是使用Vue的动态组件链接到文档

下面是关于动态组件的示例:

代码语言:javascript
复制
computed: {
  component: function () {
   return `custom-component-${this.tab}`;
 }
},

data:() => ({
  tab: 1
})

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

代码语言:javascript
复制
<component is="component"> 
<!-- instead of -->
<custom-component-number></custom-component-number>
代码语言:javascript
复制
 <component :is="component"> </component>
 <button @click="tab++"></button>

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

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

代码语言:javascript
复制
import Vue from "vue";
import Component1 from "~/components/component1.vue";
import Component2 from "~/components/component2.vue";
import Component3 from "~/components/component3.vue";

Vue.component("custom-component-1",Component1);
Vue.component("custom-component-2",Component2);
Vue.component("custom-component-3",Component3);

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

代码语言:javascript
复制
import customComponent from "~components/customComponent";
代码语言:javascript
复制
export default {
   components : {
     customComponent: "custom-component"
   }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64956166

复制
相关文章

相似问题

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