向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 -->我要研究所有可能的方法。
发布于 2020-11-22 15:48:58
使用v-if或v-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-show和v-if之间的区别。V-显示与v-if
这可能是最简单的方法,但不是最有效的。一旦您的代码变得更加复杂,这段代码将成为您的地狱。
使用Vue的动态组件
第二种方法是使用Vue的动态组件链接到文档
下面是关于动态组件的示例:
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>使用computed和is属性,我们可以动态地拥有无限个组件。这是一种很好的干净的方法。将计算部分从标记中删除,并将其放入脚本中,以获得更清晰、更高效的代码。
如果您正在使用这种方法,请确保导入和初始化要在页面中使用的组件,或者将它们添加到您的main.js 中作为全局组件,如下所示:
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);还可以将组件添加到页面中:
import customComponent from "~components/customComponent";export default {
components : {
customComponent: "custom-component"
}
}https://stackoverflow.com/questions/64956166
复制相似问题