场景:左侧菜单栏的菜单项有内部组件切换,也会有点击后进入外链的情况,如何同时处理这种情况?
解决思路:
- 在路由配置中path代表组件切换路径或者外链配置
- el-menu-item显示菜单项时,使用动态路由形式,判断如果是组件切换,使用is为router-link组件,to为path,如果是外链,使用a标签形式,path为href即可;
- 如果判断是否为外链,正则匹配是否以/^(https?:|mailto:|tel:)/.test(path)即可
路由配置:
{// 'path': '/activity','path': 'https:www.baidu.com','name': 'activity','component': Activity
}
AppLink封装:插槽形式显示el-menu-item
<template><!-- 通过动态组件显示,如果是外链显示a标签,如果是基础路由显示router-link --><!-- 这里直接使用v-bind="isExternalLink(to)"会报错,需要在上面加入一行注释:eslint-disable vue/require-component-is --><!-- eslint-disable vue/require-component-is --><component v-bind="isExternalLink(to)"><slot></slot></component>
</template>
<script>
import { Validator } from "@bigbighu/cms-utils";
export default {name: "AppLink",props: {to: {type: String,required: true}},methods: {isExternalLink(url) {// /^(https?:|mailto:|tel:)/.test(path)if (Validator.isExternal(url)) {return {is: "a",href: url,target: "_blank",rel: "noopener"};}return {is: "router-link",to: url};}}
};
</script>
el-menu-item使用:
<!-- 判断是否是外链 --><app-link v-if="child.redirect != 'noRedirect' && child.meta" :to="resolvePath(child.path)"><el-menu-item v-if="child && child.meta" :index="resolvePath(child.path)"><i class="el-icon-setting"></i><span slot="title">{{child.meta.title }}</span></el-menu-item></app-link>