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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40990854/article/details/89157765

本篇想分享两个东西

一、动态组件

动态组件的格式:就像规定的作用域插槽一样,特定的格式
	<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/[email protected]/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>

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/89157765
今日推荐