一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第20天,点击查看活动详情。
前言
在上一篇
的文章中,我们了解了vue组件中的插槽和具名插槽
的方法,今天我们继续深入了解一下vue组件中的动态组件和异步组件
。
动态组件
在第二章的内容中,我们有了解过动态元素的使用方法,主要是通过v-if
和v-show
指令来判断一个DOM元素显示还是隐藏。
如果我们要做一个动态组件是不是也可以通过v-if
和v-show
指令来判断呢?
<script>
const app = Vue.createApp({
template: `
<div>
<input-item />
<common-item />
</div>
`
});
app.component('input-item', {
template: `
<div>
<input />
</div>
`
})
app.component('common-item', {
template: `
<div>
Hello World
</div>
`
})
const vm = app.mount('#root');
</script>
首先我们会定义两个全局组件,在根组件中会使用这两个全局子组件,这时候页面上就会显示这两个子组件的内容了。如果想要动态化就可以在子组件标签上使用v-if
或者v-show
指令了。
const app = Vue.createApp({
data(){
return {
currentItem: 'input-item'
}
},
methods: {
handleClick(){
this.currentItem === 'input-item' ? this.currentItem = 'common-item' : this.currentItem = 'input-item'
}
},
template: `
<div>
<input-item v-show="currentItem === 'input-item'" />
<common-item v-show="currentItem === 'common-item'" />
<button @click="handleClick">切换</button>
</div>
`
});
-
父组件中调用子组件时,在子组件标签上添加
v-show
指令用来判断data
中的数据值。 -
通过父组件的切换按钮,来控制
v-show
指令中的值并判断组件的显示隐藏。
虽然v-show
指令已经可以很好的处理动态组件了,但是在vue里面还有一种更简单的方法去处理这种动态组件。
const app = Vue.createApp({
data() {
return {
currentItem: 'input-item'
}
},
methods: {
handleClick() {
this.currentItem === 'input-item' ? this.currentItem = 'common-item' : this.currentItem = 'input-item'
}
},
template: `
<div>
<component :is="currentItem" />
<button @click="handleClick">切换</button>
</div>
`
});
-
父组件中将子组件标签移除,替换成
component
标签。 -
在
component
标签中绑定一个is
属性,属性值就是data
中定义的数据值currentItem
。 -
使用
component
标签来做动态组件的操作,会使代码更加精简。
动态组件:根据数据的变化,结合
component
标签来随时动态切换组件的显示
异步组件
不管是上面的动态组件代码,还是以前的组件通信代码,都是一个同步执行并渲染的过程,也就是当页面加载的时候,组件都会一起渲染出来。
如果想要对某些组件进行延迟渲染,就得用到异步组件了。
定义异步组件会用到vue里面的defineAsyncComponent
方法,在这个方法里面可以定义一个Promise
去异步执行一个组件代码。
<script>
const app = Vue.createApp({
template: `
<div>
<common-item />
<async-common-item />
</div>
`
});
app.component('common-item', {
template: `
<div>
Hello World
</div>
`
})
app.component('async-common-item', Vue.defineAsyncComponent(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
template: `
<div>
这里会延迟加载!
</div>
`
})
}, 5000)
})
}))
const vm = app.mount('#root');
</script>
-
common-item
组件就是一个同步组件,会跟随页面一同被渲染出来。 -
async-common-item
组件后面调用了Vue.defineAsyncComponent
方法,在方法里面隔了5秒的时间去渲染这个组件。
异步组件:异步执行某些组件的逻辑。
总结
本篇文章主要讲了动态组件和异步组件的用法,在实际项目中,渲染同步组件会更多一些,异步组件相对运用的地方较少。但还是希望大家可以了解一下异步组件的用法,说不定某一天在项目中就碰到了。