vue-router编程式导航和a标签实现右键在新标签页中打开链接

背景

浏览器在解析a标签的时候,默认会有鼠标右键显示“在新标签页中打开链接”的功能,但有的情景不适合用a标签直接进行路由跳转。比如我遇到这个问题的项目,a标签直接跳路由会有不知道什么原因的bug。所以只能用router.push来跳转。

思路

  1. 首先排除a标签直接href跳转,我的项目会有bug。
  2. 但是最后必须要有a标签,因为这个是浏览器解析的最快最亲近的方法。
  3. 所以用到了contextmenu事件,在不鼠标右键的时候,给定一个不能直接跳转的a标签,跳转采用vue-router的方式。
  4. 在监听到contextmenu事件后,把对应的a标签替换为真正的href可以跳转的。
  5. 简单来说就是鼠标单击用vue-router,鼠标右键用a标签href

实现

  1. template部分
        <div @click="onToggleMenu(item.icon)" v-for="item in menuList" :key="item.label" class="item" :class="{active: item.icon === activeTab}"
             @contextmenu="newtab($event, item.icon, item.label)">
          <a href="javascript:void(0);">
            <svg-icon style="position: relative; z-index: 99" :icon-class="item.icon" class="svg"></svg-icon>
            <span>{
   
   {item.label}}</span>
          </a>
        </div>
  1. js部分
data() {
    
    
	return {
    
    
	      menuList: Object.freeze([{
    
     label: 'A', icon: 'a' }, {
    
     label: 'B', icon: 'b' }, {
    
     label: 'C', icon: 'c' }, {
    
     label: 'D', icon: 'd' }]),
	}
}
methods:{
    
    
    newtab(e, name) {
    
    
      const uniqueSymbol = 'TARGET#_TIGER_360~-.'; // 避免和搜索语法语句重复的字段值 color: #b8bbcc
      const replaceStr = `<a href=#/${
      
      name} style="text-decoration: none; color: #b8bbcc">`;
      const matchList = e.currentTarget.innerHTML.match(/<a.*?>/g);
      let res = e.currentTarget.innerHTML.replace(/<a.*?>/g, uniqueSymbol);
      matchList.forEach(() => {
    
    
        res = res.replace(uniqueSymbol, replaceStr);
      });
      e.currentTarget.innerHTML = res;
    },
    onToggleMenu(name) {
    
    
      this.isShowFilter = false;
      this.updatefilterisCollapse(this.isShowFilter);
      this.resetParams();
      this.changeActiveTab(name);
      this.$router.push(`/${
      
      name}`); // 跳转
    },
}

猜你喜欢

转载自blog.csdn.net/s18438610353/article/details/124862467