vue router

288 阅读2分钟

###传递参数 1.用name,面包屑导航,其它地方比较少用 插值方式,直接在需要的地方加入{{ $route.name}},需要路由里配置name 如果需要二级面包屑,就需要配置子路由

{path: '/todosimple',name: 'todosimple',component: todosimple,
    children:[
      {path:"/todosimple/left",name:"todosimple/left",component:left},
      {path:"/todosimple/right",name:"todosimple/right",component:right}
    ]
    },

2.通过router-link标签中的to传参 分两步走,第一步在源头上加参数,从哪里点(往目标去)就加那里 然后在目标位置接收参数 valueString 注意,这里的name如果是子路径,就需要带上父路径地址,参考路由里面的写法 目标位置接收参数{{$route.params.key}}

###利用url传递参数三部曲 1.配置路由 在router下面的index.js里面,先配置路由参数 {path: '/lists/:newsId/:newsTitle',name: 'lists',component: lists}, 相当于形参 2.配置链接 router-link连接里面配置实参 lists 3.接收参数 到lists页面去接收参数,以插值的形式插入即可 {{this.route.params.newsId}}
{{this.route.params.newsTitle}}

###redirect路由重定向 只要在路由配置文件中(/src/router/index.js)把原来的component换成redirect参数就可以了 { path:'/goback', redirect:'/' }

###路由中的钩子 可以在两个地方写,一个是路由文件里,一个是组件script里 路由文件里,只能写beforEnter,如下案例 {path: '/users',name: 'users',component: users, beforeEnter:(to,from,next)=>{ console.log(to); console.log(from); next(); } },

另外一个写法是写到组件的script里,当做一个组件函数 beforeRouteEnter(to,from,next){ console.log(to); console.log(from); next(); }, ###编程式导航

第一种,使用go方法:this.$router.go(-1) 
第二种,编程式push:this.$router.push('/home')

###路由高亮的实现 加一个css规则即可 .router-link-active{ color: red; }

###动态路由和get传值 配置动态路由,动态路径参数以冒号开头 路由里面的配置{ path: '/user/:id', component: User } 源地址处配置{{key}}--{{item}} 目标地址mounted获取console.log(this.$route.params);

配置get传值 路由里面不做更改,{ path: '/news',component: news}, 源地址处配置{{key}}--{{item}} 目标地址mounted获取console.log(this.$route.query);

路由鉴权的实现,比如先判断是否登录,登录才可以进入管理页面

1. 在router.js文件里设置路由的meta信息
{path: '/admin',name: 'admin',component: Admin,meta:{type:"admin"}}

2. 全局main.js下设置路由守卫
router.beforeEach((to, from, next) => {
  console.log(to.meta.type);
  let toUrl = to.meta.type;
  if (toUrl == "admin") {
    if (window.localStorage.getItem("login")) {
      next()
    } else {
      next("/login")
    }
  } else {
    next()
  }
})
意思是,当检测到需要进入admin的时候,如果获得了localStorage的存值就继续,否则就跳转到login页面去登录设置localStorage

区别this.router和this.route this.router调用的是整个路由配置,一般用来修改当前路径,如this.router.push("/about"),或者replace方法替代 this.route调用的是当前激活页面的路由信息,一般用来查询参数如this.route.params.id

路由守卫,