<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
效果性能
下面这段代码实现的效果和上面是同样的。this
<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
里面数据的变化,会自动的加载不一样的组件code
v-noce
指令每次点击按钮切换的时候,Vue 底层会帮咱们干什么呢?Vue 底层会判断这个child-one
组件如今不用了,取而代之要用child-two
组件,而后它就会把child-one
组件销毁掉,在建立一个child-two
组件。假设这时child-two
组件要隐藏,child-one
组件要显示,这个时候要把刚刚建立的child-two
销毁掉,在从新建立child-one
组件,也就是每一次切换的时候,底层都是要销毁一个组件,在建立一个组件,这种操做会消耗必定的性能。若是咱们的组件的内容,每次都是同样的能够在上面加一个v-once
,看下面代码。component
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
指令,能够提升一些静态内容的展现效率效率