【问题标题】:How to compare two routes by hand如何手动比较两条路线
【发布时间】:2019-05-20 20:39:57
【问题描述】:

我如何手动(以编程方式)比较两条路线并确定它们是否相同? (如果存在router-link-activerouter-link-exact-active

一般我需要这种功能

/* 
   @params route1, route2 : Route
*/
function isActivated(route1, route2) {
  /* comparing them somehow */
  return {
    exactActive,
    active
  };
}

用例: 我有一个NestedLink.vue 组件,它是router-link 的包装器。 它需要torouter-link 一样的属性(并将其传递给子路由器链接)。如果当前路由处于活动状态,嵌套链接将出现在附近。

我的方法

function isActivated(route1, route2) {
  if (
    route1.matched.some(record =>
      record.regex.test(route2.fullPath)
    )
  ) {
    return { exactActive: true };
  }
  return { exactActive: false };
}

它可以判断路线何时是exact-active,但不是not-exact-active

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    这是在 router-link 组件中使用的代码。

    const START = '/';
    const trailingSlashRE = /\/?$/;
    
    function isObjectEqual (a, b) {
      if ( a === void 0 ) a = {};
      if ( b === void 0 ) b = {};
    
      // handle null value #1566
      if (!a || !b) { return a === b }
      var aKeys = Object.keys(a);
      var bKeys = Object.keys(b);
      if (aKeys.length !== bKeys.length) {
        return false
      }
      return aKeys.every(function (key) {
        var aVal = a[key];
        var bVal = b[key];
        // check nested equality
        if (typeof aVal === 'object' && typeof bVal === 'object') {
          return isObjectEqual(aVal, bVal)
        }
        return String(aVal) === String(bVal)
      })
    }
    
    function isSameRoute (a, b) {
      if (b === START) {
        return a === b
      } else if (!b) {
        return false
      } else if (a.path && b.path) {
        return (
          a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
          a.hash === b.hash &&
          isObjectEqual(a.query, b.query)
        )
      } else if (a.name && b.name) {
        return (
          a.name === b.name &&
          a.hash === b.hash &&
          isObjectEqual(a.query, b.query) &&
          isObjectEqual(a.params, b.params)
        )
      } else {
        return false
      }
    }
    

    那么,下面是如何在组件中使用它:

    // OR JUST A STRING '/home'
    let link = { name: 'home' } 
    // will return true of false
    let result = isSameRoute(this.$router.resolve(link).resolved, this.$route)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多