Vue 动态组件

最近读到一篇关于Vue实现内部组件轮播切换效果文章,发现非常有意思,这里就记录一下实现的方法

原文章地址

Vue实现内部组件轮播切换效果

原理

通过<component>元素渲染一个“元组件”为动态组件。依 is 的值,来决定哪个组件被渲染。

实践

重点在component元素这段代码,通过它的is值,动态地加载组件实现切换。在组件初始化的时候,给questions进行赋值操作,然后在点击下一步的时候改变当前的currentIndex的值,动态读取questionstype属性即可实现动态组件加载。

app.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<template>
<div id="app">
<div class="task-container">
<!-- 重点在下面这段代码,通过component的is值,动态地加载组件实现切换 -->
<component :is="'task-' + questions[currentIndex].type" :question="questions[currentIndex]"></component>
<button class="next-question" @click="nextQuestion">下一题</button>
</div>
</div>
</template>

<script>
import Task1 from "./components/task-1";
import Task2 from "./components/task-2";
import Task3 from "./components/task-3";

export default {
name: "App",
data() {
return {
currentIndex: 0,
questions: []
};
},
methods: {
nextQuestion() {
this.currentIndex = (this.currentIndex + 1) % this.questions.length;
}
},
created() {
this.questions = [
{ index: 1, type: 1, content: "这里是 Task1 组件" },
{ index: 2, type: 2, content: "这里是 Task2 组件" },
{ index: 3, type: 3, content: "这里是 Task3 组件" },
];
},
components: {
Task1,
Task2,
Task3
}
};
</script>

task-1.vue

1
2
3
4
5
6
7
8
9
10
11
12
<template>
<section>
<h2>{{question.index}}. 选择题</h2>
<div>{{question.content}}</div>
</section>
</template>

<script>
export default {
props: ["question"]
};
</script>

task-2.vue、task-3.vue 同上