这是我参与8月更文挑战的第19天,活动详情查看:8月更文挑战
场景需求
在某些场景,往往需要我们动态切换页面部分区域的视图,传统的用法是:采用v-if 来设置组件的状态。如下:
<div id="app">
<child-one v-if="this.type === 'child-one'"></child-one>
<child-two v-if="this.type === 'child-two'"></child-two>
<button type="button" @click="handleTogge">切换</button>
</div>
Vue.component('child-one',{
template:`<div>child-one</div>`
})
Vue.component('child-two',{
template:`<div>child-two</div>`
})
var vm = new Vue({
el: '#app',
data: function() {
return {
type: 'child-one'
}
},
methods:{
handleTogge: function() {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
这样也能完成toggle效果,但是很显然,代码很繁琐。这个时候 Vue 提供的内置组件 component 就显得尤为重要。
动态组件component
component 会接收一个名为"is"的属性;is的属性值是在父组件中注册过的组件的名称。
用法如下:
<div id="app">
<component :is="type"></component>
<button type="button" @click="handleTogge">切换</button>
</div>
// js部分同上
keep-alive
提到上述动态组件不得不说下keep-alive, keep-alive 是 Vue 的内置组件,当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 transition 相似,keep-alive 是一个抽象组件:它自身不会渲染成一个 DOM 元素,也不会出现在父组件链中。
作用: 组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性。
应用场景: 如果未使用 keep-alive 组件,则在页面回退时仍然会重新渲染页面,触发created钩子,使用体验不好。比如在菜单存在多级关系,列表页+详情页的场景,比如:
- 商品列表页点击商品跳转到商品详情,返回后仍显示原有信息。
- 订单列表跳转到订单详情,返回,等等场景。
以上场景中使用 keep-alive 组件会显著提高用户体验。
使用方法: 将组件世界包裹在keep-alive中,这样组件的状态将会被保留。
<keep-alive>
<component :is="type" v-once></component>
</keep-alive>
v-once指令
应用场景: 如果显示的信息后续不需要再修改,使用v-once,这样可以提高性能。
上述代码增加v-once后,<component :is="type" v-once></component> 只渲染初次加载的内容,点击按钮后将不再进行切换。