Vue---动态组件与v-once

527 阅读2分钟

动态组件的引入

我们需要完成一个点击按钮显示不同子组件的代码

<div id="root">
	<child-one v-if="type === 'child-one'"></child-one>
	<child-two v-if="type === 'child-two'"></child-two>
	<button @click="handleBtnClick">change</button>
</div>

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

	Vue.component('child-two',{
		template:'<div>child-two</div>'
	})

	var vm = new Vue({
		el:'#root',
		data:{
			type:'child-one'
		},
		methods:{
			handleBtnClick:function(){
				this.type = (this.type === 'child-one' ? 'child-two' : 'child-one');
			}
		}
	})
</script>

我们使用v-if对两个子组件的布尔值进行改变,并添加点击函数来完成目的,但代码略显复杂

动态组件

还是上面的例子,我们使用动态组件来完成

<div id="root1">
	<component :is="num"></component><!-- 动态组件 -->
	<button @click="handleBtnClick">change</button>
</div>

<script type="text/javascript">
	Vue.component('child-three',{
		template:'<div>child-three</div>'
	})
	Vue.component('child-four',{
		template:'<div>child-four</div>'
	})

	var vm = new Vue({
		el:'#root1',
		data:{
			num:'child-three'
		},
		methods:{
			handleBtnClick:function(){
				this.num = (this.num === 'child-three' ? 'child-four' : 'child-three');
			}
		}
	})
</script>

动态组件的定义

在Vue中,定义了一种标签<component></component>,这个标签即为动态组件

动态组件的使用

在component标签内有一个is属性,令is属性的值在不同时候等于不同的子组件名称,即可完成组件的动态转换

使用动态组件时需要对所会应用上的子组件进行声明定义

v-once指令

再次分析引例的代码,由于使用了v-if进行 子组件的切换,v-if的特性使得当我们在切换时会对上一次渲染的子组件进行销毁再重新进行渲染,但切换的内容只有两种,重复的渲染与销毁极大的浪费了性能

为了解决性能的浪费,我们在子组件定义模板的时候给标签添加v-once属性,这样渲染过一次的子组件就会保存在内存之中,下次调用时不必重复渲染,可以提高静态内容的展示效率

js代码修订:

Vue.component('child-one',{
		template:'<div v-once>child-one</div>'
	})

	Vue.component('child-two',{
		template:'<div v-once>child-two</div>'
	})