Vue 动态组件与 v

<div> <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> <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> <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指令,可以提高一些静态内容的展示效率

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3c3a2ff37de3e34c70baa02f61fb2d51.html