文档
component动态组件很适合在不同组件之间切换,相比v-if
判断,要优雅得多
项目结构
$ tree -I node_modules . ├── package.json └── src ├── App.vue ├── components │ ├── ComponentA.vue │ ├── ComponentB.vue │ └── ComponentC.vue └── main.js
依赖 package.json
{ "scripts": { "dev": "vue-cli-service serve", "build": "vue-cli-service build" }, "dependencies": { "vue": "^2.6.14" }, "devDependencies": { "@vue/cli-service": "^5.0.8", "vue-template-compiler": "^2.6.14", "less": "^4.0.0", "less-loader": "^8.0.0" } }
入口文件 main.js
import Vue from "vue"; import App from "./App.vue"; new Vue({ el: "#app", render: (h) => h(App), });
组件 ComponentA.vue
<template> <div class="">ComponentA</div> </template> <script> // created at 2023-03-31 export default { name: "ComponentA", }; </script> <style lang="less"></style>
组件 ComponentB.vue
<template> <div class="">ComponentA</div> </template> <script> // created at 2023-03-31 export default { name: "ComponentA", }; </script> <style lang="less"></style>
组件 ComponentC.vue
<template> <div class="">ComponentC</div> </template> <script> // created at 2023-03-31 export default { name: "ComponentC", }; </script> <style lang="less"></style>
App.vue
<template> <div class="app-container"> <h2>Vue.js component动态组件示例</h2> <!-- tabs --> <div class="tabs"> <div v-for="item in componentConfigs" class="tab-item" :class="{ 'tab-item--active': item.value == tab }" @click="handleTabClick(item)" > {{ item.label }} </div> </div> <!-- content --> <div class="content"> <component v-bind:is="currentComponent"></component> </div> </div> </template> <script> // created at 2022-12-26 import ComponentA from "./components/ComponentA.vue"; import ComponentB from "./components/ComponentB.vue"; import ComponentC from "./components/ComponentC.vue"; const componentConfigs = [ { component: ComponentA, value: "A", label: "组件 A", }, { component: ComponentB, value: "B", label: "组件 B", }, { component: ComponentC, value: "C", label: "组件 C", }, ]; export default { name: "App", data() { return { tab: "A", componentConfigs, }; }, computed: { currentComponent() { return componentConfigs.find((item) => item.value == this.tab).component; }, }, methods: { handleTabClick(item) { this.tab = item.value; }, }, created() {}, }; </script> <style lang="less"> body { display: flex; justify-content: center; } .app-container { text-align: center; } .tabs { display: flex; justify-content: center; border: 1px solid #808080; border-bottom: none; } .tab-item { width: 200px; line-height: 40px; text-align: center; background-color: #808080; color: #fff; cursor: pointer; } .tab-item--active { background-color: #fff; color: #000; } .content { line-height: 500px; text-align: center; border: 1px solid #808080; } </style>
完整代码:https://github.com/mouday/vue-demo/tree/main/packages/vue-component
在线示例:https://mouday.github.io/vue-demo/packages/vue-component/dist/index.html