动态组件
让多个组件使用同一个<component></component>挂载点,并动态切换组件。
其具体实现是在一个多标签的界面中使用 is 属性来动态切换不同的组件,如:
1 2 |
<!--在component中使用is属性绑定组件--> <component v-bind:is="currentTabComponent"></component> |
动态组件具体实现如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<template> <div> <button @click="change">动态组件切换</button> <!--动态组件--> <component :is="currentComponent"></component> </div> </template> <script> export default { // 引入组件 components: { one: { template: "<div>组件1</div>" }, two: { template: "<div>组件2</div>" }, three: { template: "<div>组件3</div>" }, }, data: { index: 0, arr: ["one", "two", "three"], // 初始组件信息 currentComponent: "one", }, methods: { // 动态切换组件 change() { //取余 this.index = ++this.index % 3; //切换组件 this.currentComponent = this.arr[this.index]; }, }, } </script> |
条件判断组件动态加载
除了通过动态组件的形式实现组件的动态切换,也可以通过多条件判断的方式实现组件的切换,具体实现如下:
1 2 3 4 5 6 7 8 9 10 |
<!-- 多个条件判断的子组件 --> <template> <div> <button @click="change">动态组件切换</button> <!-- 多个条件判断的子组件 --> <one v-if="currentComponent == 'one'"></one> <two v-else-if="currentComponent == 'two'"></two> <threev-else></three> </div> </template> |
动态组件缓存
动态组件在组件之间切换的时候,会重复渲染组件的内容,但对于有些想保持组件状态的场景来说,会出现反复重渲染导致的性能问题。
为了解决切换时重新创建组件的问题,我们可以用一个 <keep-alive> 元素将动态组件包裹起来,实现页面组件的缓存效果,具体实现如下:
1 2 3 4 5 6 7 8 9 |
<template> <div> <button @click="change">动态组件切换</button> <!-- 失活的组件将会被缓存!--> <keep-alive> <component :is="currentComponent"></component> </keep-alive> </div> </template> |
<keep-alive> 元素会缓存不活动的组件实例,而不是销毁它们。
<keep-alive> 元素在多条件判断的子组件的应用如下:
1 2 3 4 5 6 7 8 9 10 11 |
<template> <div> <button @click="change">动态组件切换</button> <!-- 多个条件性的子元素 --> <keep-alive> <one v-if="currentComponent == 'one'"></one> <two v-else-if="currentComponent == 'two'"></two> <three v-else></three> </keep-alive> </div> </template> |
本文来自作者:爆点游戏社,不代表小新网立场!
转载请注明:https://www.xiaoxinys.cn/101855.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。