vue动态组件

    科技2022-08-02  106

    动态组件

    有的时候,我们需要在多个不同的组件之间进行切换。虽然我们可以通过 v-if 来处理,但是会比较麻烦,vue 提供了一个更方便的方式来处理这种情况

    component 组件

    component 是 vue 内置的一个组件,它提供一个 is 属性用来动态渲染不同的组件

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .current { background: yellow; } </style> </head> <body> <div id="app"> <button @click="goto('InBox')" :class="{'current': currentComponent==='InBox'}">收邮件</button> <button @click="goto('PostMail')" :class="{'current': currentComponent==='PostMail'}">发邮件</button> <button @click="goto('RecycleBin')" :class="{'current': currentComponent==='RecycleBin'}">垃圾箱</button> <hr> <component :is="currentComponent"></component> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const InBox = { data() { return { items: [ '111111', '22222222222', 'aaaaaaaa', '3333333' ] } }, template: ` <div> <ul> <li v-for="item of items"> <input type="checkbox" /> {{item}} </li> </ul> </div> `, created() { console.log('InBox:created'); }, destroyed() { console.log('InBox:destroyed'); } } const PostMail = { template: ` <div>PostMail</div> `, created() { console.log('PostMail:created'); }, destroyed() { console.log('PostMail:destroyed'); } } const RecycleBin = { template: ` <div>RecycleBin</div> `, created() { console.log('RecycleBin:created'); }, destroyed() { console.log('RecycleBin:destroyed'); } } let app = new Vue({ el: '#app', data: { currentComponent: 'InBox' }, components: { InBox, PostMail, RecycleBin }, methods: { goto(target) { this.currentComponent = target; } } }); </script> </body> </html>

    我们会发现,当组件切换的时候,都会触发组件的销毁和重建。首先,性能不好。其次,会丢失组件状态

    keep-alive 组件

    当在这些组件之间切换的时候,有时会想保持这些组件的状态,以避免反复重渲染导致的性能问题。keep-alive 是一个内置容器组件, 使用 >keep-alive 以后,内部包含的组件将增加 激活 和 失活/冻结 的状态

    <keep-alive> <component :is="currentComponent"></component> </keep-alive>

    生命周期

    使用了 keep-alive 的组件会触发 activated、deactivated 两个生命周期函数

    activated

    keep-alive 组件激活时调用

    deactivated

    keep-alive 组件停用时调用

    Processed: 0.010, SQL: 8