动态组件与 v-once 指令
栏目: JavaScript · 发布时间: 6年前
内容简介:上面代码需实现,当点击按钮时,通过上面下面这段代码实现的效果和上面是一样的。
<div id="root">
<child-one></child-one>
<child-two></child-two>
<button>change</button>
</div>
Vue.component('child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`,
})
let vm = new Vue({
el: '#root'
})
上面代码需实现,当点击按钮时, child-one
和 child-two
实现 toggle
效果,该怎么实现呢?
<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>
Vue.component('child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`,
})
let vm = new Vue({
el: '#root',
data: {
type:'child-one'
},
methods: {
handleBtnClick(){
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
通过上面 handleBtnClick
函数的实现,配合 v-if
指令就能实现 toggle
效果
动态组件
下面这段代码实现的效果和上面是一样的。
<div id="root">
<component :is="type"></component> //is内容的变化,会自动的加载不同的组件
<button @click="handleBtnClick">change</button>
</div>
Vue.component('child-one', {
template: `<div>child-one</div>`,
})
Vue.component('child-two', {
template: `<div>child-two</div>`,
})
let vm = new Vue({
el: '#root',
data: {
type:'child-one'
},
methods: {
handleBtnClick(){
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
动态组件的意思是它会根据 is
里面数据的变化,会自动的加载不同的组件
v-noce
指令
每次点击按钮切换的时候,Vue 底层会帮我们干什么呢?Vue 底层会判断这个 child-one
组件现在不用了,取而代之要用 child-two
组件,然后它就会把 child-one
组件销毁掉,在创建一个 child-two
组件。假设这时 child-two
组件要隐藏, child-one
组件要显示,这个时候要把刚刚创建的 child-two
销毁掉,在重新创建 child-one
组件,也就是每一次切换的时候,底层都是要销毁一个组件,在创建一个组件,这种操作会消耗一定的性能。如果我们的组件的内容,每次都是一样的可以在上面加一个 v-once
,看下面代码。
Vue.component('child-one', {
template: `<div v-once>child-one</div>`,
})
Vue.component('child-two', {
template: `<div v-once>child-two</div>`,
})
加上 v-once
指令之后,有什么好处呢?当 chlid-one
组件第一次被渲染时,因为组件上面有一个 v-once
指令,所以它直接就放到内存里了,当切换的时候 child-two
组件第一次被渲染时,它也会被放到内存里,再次点击切换时,这时并不需要再重新创建一个 child-one
组件了,而是从内存里直接拿出以前的 child-one
组件,它的性能会更高一些。
所以在 Vue 当中,通过 v-once
指令,可以提高一些静态内容的展示效率
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Hit Refresh
Satya Nadella、Greg Shaw / HarperBusiness / 2017-9-26 / USD 20.37
Hit Refresh is about individual change, about the transformation happening inside of Microsoft and the technology that will soon impact all of our lives—the arrival of the most exciting and disruptive......一起来看看 《Hit Refresh》 这本书的介绍吧!