Vue 點擊顯示不同的 component

環境

"vue": "^2.6.14"

範例

建立組件

假如說有 A,B,C 三個組件

import Aexample from "./components/Aexample.vue";
import Bexample from "./components/Bexample.vue";
import Cexample from "./components/Cexample.vue";

Vue.component("a-example", Aexample);
Vue.component("b-example", Bexample);
Vue.component("c-example", Cexample);

動態組件

vue2

<component v-bind:is="componentName"></component>

vue3

<div v-is="componentName"></div>

點擊切換組件

在 Html 中利用點擊切更換currentComponent變數,賦予給componenttag,預設情況下會先顯示a-example的組件,隨使用者點擊會切換不同的組件

<div id="app">
<nav class="nav nav-pills nav-fill mb-3 align-items-center">
<a
class="nav-link btn btn-outline-primary"
data-toggle="tab"
:class="{ active : currentComponent == 'a-example' }"
href="#"
@click="currentComponent = 'a-example'"
>A</a
>
<a
class="nav-link btn btn-outline-primary"
data-toggle="tab"
:class="{ active : currentComponent == 'b-example' }"
href="#"
@click="currentComponent = 'b-example'"
>B</a
>
<a
class="nav-link btn btn-outline-primary"
data-toggle="tab"
:class="{ active : currentComponent == 'c-example' }"
href="#"
@click="currentComponent = 'c-example'"
>C</a
>
</nav>
<div class="tab-content p-5">
<div class="tab-pane fade show active" id="detect-class">
<component :is="currentComponent"></component>
</div>
</div>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
currentComponent: "a-example", // name of your component
},
});
</script>

prop 資料

當然如果有需要 props 的資料也可以

<component :is="currentComponent" v-bind:variable="variable"></component>

後計

也可以將組件組成陣列的方式

const app = new Vue({
el: "#app",
data: {
currentComponent: "a-example", // name of your component
list: [
{ name: "A範例", componentName: "a-example" },
{ name: "B範例", componentName: "b-example" },
{ name: "C範例", componentName: "c-example" },
],
},
});

利用v-for循環將a tag顯示

<a
class="nav-link btn btn-outline-primary"
data-toggle="tab"
:class="{ active : currentComponent == value.componentName }"
href="#"
@click="currentComponent = value.componentName"
v-for="(value, index) in list"
:key="value.name"
>{{ value.name }}</a
>