---
# System prepended metadata

title: Vue點擊顯示不同的component
tags: [' Vue', Javascript]

---

---
tags: Javascript, Vue
---

# Vue點擊顯示不同的component

## 環境

`"vue": "^2.6.14"`

## 範例

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

```javascript=
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

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

#### vue3

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

### 點擊切換組件

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

```htmlembedded=
<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>`

### 後計

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

```javascript=
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`顯示

```htmlmixed=
<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>
```