如何手动比较两条路线

时间:2018-12-20 10:23:56

标签: vue.js vue-router

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

通常我需要这种功能

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

用例: 我有一个NestedLink.vue组件,它包装在router-link上。 它与to一样使用router-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

1 个答案:

答案 0 :(得分:0)

这是在路由器链接组件内部使用的代码。

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)