十一、动态组件与v-once指令

本篇想分享两个东西

一、动态组件

动态组件的格式:就像规定的作用域插槽一样,特定的格式
	<component :is='type'></component>
	
其中的 :is 用来指明是哪一个组件,如果是就会创建该组件,不是就会销毁该组件
			不管是 动态组件还是 if 组件每次都是在反复创建 和 销毁,这样对性能有一定的影响

二、v-once指令

v-once 修饰的组件,一经创建,就会保存在内存中,不会被销毁,在需要时直接使用

通过 v-once 就可以解决上面反复创建和销毁问题
	template:'<div v-once>child-one</div>
在组件的模板中添加 v-once ,子组件一经创建,就会保存在内存中,不会被销毁,在需要时直接使用

动态组件与v-once指令Demo

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>动态组件与v-once指令</title>
	<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>
<body>
	<div id="root">
		<!-- 
			动态组件 
			<component :is='type'></component>
			其中的 :is 用来指明是哪一个组件,如果是就会创建该组件,不是就会销毁该组件
			不管是 动态组件还是 if 组件每次都是在反复创建 和 销毁,这样对性能有一定的影响
			通过 v-once 来解决这个问题
				template:'<div v-once>child-one</div>'
			在组件的模板中添加 v-once ,子组件一经创建,就会保存在内存中,不会被销毁,在需要时直接使用
		-->
		<component :is='type'></component>
	<!-- 		
		<child-one v-if='type === "child-one"'></child-one>
		<child-two v-else></child-two> 
	-->
		<button @click='handleClick'>change</button>
	</div>

	<script type="text/javascript">
		Vue.component('child-one',{
			template:'<div v-once>child-one</div>'
		});
		Vue.component('child-two',{
			template:'<div v-once>child-two</div>'
		});

		var vm = new Vue({
			el:'#root',
			data:{
				type:'child-one'
			},
			methods:{
				handleClick:function () {
					this.type = this.type === 'child-one' ? 'child-two' : 'child-one' 
				}
			}
		});
	</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值