vue常用的路由对象

官网上解释:一个路由对象表示当前激活的路由的状态信息

路由对象,在组件内即this.$route,存着一些与路由相关的信息,当路由切换时,路由对象会被更新

//如果要在刷新页面时候通过路由的信息来操作数据,可以在created下使用this.$route 这个属性

$route.name 

当前路由的名称,如果没有使用具名路径,则名字为空

$route.path

字符串,等于当前路由对象的路径,会被解析为绝对路径

一般为#后面的部分,但不包含query查询值

如:

http://example.com/#/login?name=aa
this.$route.path;    //输出“/login”

$route.fullPath

完成解析后的URL路径,包括查询信息和hash的完整路径

http://example.com/#/login?name=aa
this.$toute.fullPath;    //输出“/login?name=aa”

 $route.meta

在路由里面埋一个字段,当切换路由时候把信息传过去

在meta对象中可以设置一些状态,来进行一些操作(比如做登录校验)

{
  path: '/actile',
  name: 'Actile',
  component: Actile,
  meta: {
    login_require: false
  },
},
{
  path: '/goodslist',
  name: 'goodslist',
  component: Goodslist,
  meta: {
    login_require: true
  },
  children:[
    {
      path: 'online',
      component: GoodslistOnline
    }
  ]
}
//只需要判断item下面的meta对象中的login_require是不是true,就可以做一些限制操作
router.beforeEach((to, from, next) => {
  if (to.matched.some(function (item) {
    return item.meta.login_require
  })) {
    next('/login')
  } else 
    next()
})

 $route.matched

一个数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象,从父路由(如果有)到当前路由为止

$route.query 

查询信息包含路由中查询参数的键值对

如:

this.$router.push({name: 'login', query:{name: 'you'}})

此时路由为

http://example.com/#/login?name=you
this.$route.query.name;    //输出you

$route.hash

当前路径的哈希值,带#

$route.params

预设的变量(设了之后可以取),切换时候,通过parmas带过去某个id的值

如果使用params,就不能定义path,改为name来引用

$route.redirectedFrom

重定向。如果存在重定向,即为重定向来源的路由名字

如:

{ path: '*',redirect: {name: 'hello'}}

此时访问不存在的路由http://example.com/#/a会重定向到hello

在hello访问

this.$route.redirectedFrom;    //输出“/a”
原文地址:https://www.cnblogs.com/theblogs/p/10478369.html