vue 动态组件使用教程
vue 动态组件的使用,下面进行介绍1、基本使用新建组件 Article.vue<template><div><p>黄州东南三十里为沙湖,亦曰螺师店。予买田其间,因往相田得疾。</p><p>闻麻桥人庞安常善医而聋。遂往求疗。</p><p>安常虽聋,而颖悟绝人,以纸画字,书不数字,辄深了人意。</p>&l
·
vue 动态组件的使用,下面进行介绍
1、基本使用
新建组件 Article.vue
<template>
<div>
<p>黄州东南三十里为沙湖,亦曰螺师店。予买田其间,因往相田得疾。</p>
<p>闻麻桥人庞安常善医而聋。遂往求疗。</p>
<p>安常虽聋,而颖悟绝人,以纸画字,书不数字,辄深了人意。</p>
<p>余戏之曰:“余以手为口,君以眼为耳,皆一时异人也。”</p>
<p>疾愈,与之同游清泉寺。</p>
<p>寺在蕲水郭门外二里许,有王逸少洗笔泉,水极甘,下临兰溪,溪水西流。</p>
<p>余作歌云:“山下兰芽短浸溪,松间沙路净无泥,萧萧暮雨子规啼。</p>
<p>谁道人生无再少?君看流水尚能西,休将白发唱黄鸡。”</p>
<p>是日剧饮而归。</p>
</div>
</template>
新建组件 Poetry.vue
<template>
<div>
<p>春宵</p>
<p>苏轼 </p>
<p>春宵一刻值千金,花有清香月有阴。</p>
<p>歌管楼台声细细,秋千院落夜沉沉。</p>
</div>
</template>
新建 Learn.vue
并在 Learn.vue 中引入 Article.vue 和 Poetry.vue
本文中 Learn.vue 、Article.vue、Poetry.vue 在同一文件夹下
<template>
<div>
<component :is="currentComponent"></component>
<button @click="changeComponent">修改组件</button>
</div>
</template>
<script>
import Article from './Article.vue'
import Poetry from './Poetry.vue'
export default {
components: {
Article,
Poetry
},
data() {
return {
currentComponent: 'Article'
}
},
methods: {
changeComponent() {
this.currentComponent = 'Poetry'
}
}
}
</script>
动态组件,即使用 component 标签,通过 is 属性指定的名称来切换不同的组件
运行效果
2、配合 keep-alive 使用
keep-alive 可以保持这些组件的状态,如果需要保持组件的状态,则需要配合 keep-alive 一起使用
先看需要保持状态,而不使用 keep-alive 的情况
新建 Manuscript.vue
<template>
<div>
<form action="">
<input type="text" name="title" />
<br>
<input type="text" name="content" />
</form>
</div>
</template>
修改 Learn.vue
<template>
<div>
<component :is="currentComponent"></component>
<button @click="changeComponent(1)">诗歌</button>
<button @click="changeComponent(2)">稿件</button>
</div>
</template>
<script>
import Poetry from './Poetry.vue'
import Manuscript from './Manuscript.vue'
export default {
components: {
Poetry,
Manuscript
},
data() {
return {
currentComponent: 'Poetry'
}
},
methods: {
changeComponent(type) {
if(type == 1) {
this.currentComponent = 'Poetry'
}
if(type == 2) {
this.currentComponent = 'Manuscript'
}
}
}
}
</script>
运行效果
看运行效果,会发现在 稿件 中输入文字后,切回到 诗歌,再回到 稿件,之前的 稿件 信息就不见了
出现这个情况的原因是,每次切换新组件的时候,Vue 都创建了一个新的组件。因此,如果需要保存原来的组件信息,要配合 keep-alive 使用
添加 keep-alive 后的 Learn.vue
使用 <keep-alive>
标签将动态组件包裹起来
<template>
<div>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
<button @click="changeComponent(1)">诗歌</button>
<button @click="changeComponent(2)">稿件</button>
</div>
</template>
<script>
import Poetry from './Poetry.vue'
import Manuscript from './Manuscript.vue'
export default {
components: {
Poetry,
Manuscript
},
data() {
return {
currentComponent: 'Poetry'
}
},
methods: {
changeComponent(type) {
if(type == 1) {
this.currentComponent = 'Poetry'
}
if(type == 2) {
this.currentComponent = 'Manuscript'
}
}
}
}
</script>
运行效果
至此完
更多推荐
已为社区贡献16条内容
所有评论(0)