场景:
在实际项目开发中,我们经常会遇到选项卡切换,对于一个前端工程师来说,组件化/模块化开发是一种必备的行为规范,我们经常会把每个选项卡的主体作为一个单独的组件,然后通过v-if/v-show来判断显示当前选项卡,这样的话我们就要将所有的组件都要注册并使用,代码会有点冗余,今天分享一个可以简化代码的骚操作。
代码:
<template>
<div class="about">
<button @click="checkComponent">点击随机切换A B C组件</button>
<hr>
<!-- 固定的组件 -->
<component is="A"></component>
<!-- 动态组件切换 -->
<component :is="toggle"></component>
<hr>
</div>
</template>
<script>
import A from "./A.vue";
import B from "./B.vue";
import C from "./C.vue";
export default {
data(){
return {
toggle: B,
arrComponents: [A, B, C]
}
},
methods: {
checkComponent(){
this.toggle = this.arrComponents[Math.random() * (this.arrComponents.length) | 0]
}
},
components: {
A,
B,
C
}
}
</script>
具体问题具体分析,这些只是大的方向,喜欢的可以自己尝试~~