element标签页tabs二次封装(vue动态组件)

封装

循环遍历标签页,其中的if判断用于解决切换页面闪烁问题

vue 提供了一个内置的<component>组件,专门用来实现动态组件的渲染

 <el-tabs v-model="activeName">
      <el-tab-pane
        v-for="item in aComponents"
        :label="item.label"
        :name="item.name"
        :key="item.name"
      >
        <!--2.通过is属性,动态指定要渲染的组件-->
        <component v-if="item.name == activeName" :is="item.compon" />
      </el-tab-pane>
    </el-tabs>

这里用到vue的混入,方便多个页面直接引用相关代码

<script>
import Interface from "./components/Interface.vue";
import officialDocument from "./components/officialDocument.vue";
import Retrieving from "./components/Retrieving.vue";
import reviewError from "./components/reviewError.vue";
import MyMixin from "../../common/mixin";
//动态传参渲染标签页
let mixin = new MyMixin({
  aComponents: [
    {
      name: "log0",
      label: "检索日志",
      compon: "Interface",
    },
    {
      name: "log1",
      label: "接口日志",
      compon: "officialDocument",
    },
  ],
});
export default {
  mixins: [mixin],
  components: {
    Interface,
    officialDocument,
  },
};
</script>

mixin.js

export default function MyMixin(e) {
    let {
        aComponents,
    } = e
    return {
        data() {
            return {
                aComponents: aComponents,
                //默认高亮第一个标签页
                activeName: aComponents[0].name,
            };
        },
        watch: {
            $route() {
                //路由切换有携带参数的话标签页对应高亮跳转,否则第一个高亮
                if (this.$route.query.tab) {
                    this.activeName = this.$route.query.tab;
                } else {
                    this.activeName = this.aComponents[0].name;
                }
            },
        },
    }
}

补充:

默认情况下,vue切换动态组件时无法保持组件的状态。此时可以使用 vue 内置的 组件保持动态组件的状态,示例代码如下:

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

keep-alive 对应的生命周期函数

当组件被缓存时,会自动触发组件的 deactivated 生命周期函数。当组件被激活时,会自动触发组件的 activated 生命周期函数。

export default {
  crkated(){ console.log('组件被创建了') },
  destroyed(){console.log('组件被销毁了')},
  
  activated(){console.log('Left组件被激活了!')},
  deactivated(){console.log('Left组件被缓存了!') }
}

keep-alive 的 include 属性

include 属性用来指定:只有名称匹配的组件会被缓存。多个组件名之间使用英文的逗号分隔:

<keep-alive include="MyLeft,MyRight">
  <component :is="comName"></component>
</keep-alive>

猜你喜欢

转载自blog.csdn.net/weixin_52691965/article/details/128535653