您的位置:首页 > Web前端 > Vue.js

Vue-路由/守卫

2019-05-27 15:22 381 查看

路由

路由的定义

1.在URL中采用#号老作为当前视图的地址,改变#号后的参数,页面不会重载。

路由顺序文本定义
  • 1.下载 vue-router
  • 2.新建一个router文件夹,在这个文件夹下面新建一个index.js(路由的配置文件)
- 引入vue
- 引入 vue-router
- use注册路由实例
- 配置路由信息 routers:{path:"/[,compntent":""}]
- 把配置的路由信息挂载到实例上
- 抛出实例

-3.在mian.js里面,挂载路由实例

4. router-view
<router--view></router-view>  //输出视图,它是vue-router的内置插件,需要先注意下vueRouter
4-1
<router-link to="里面写路径,带/"></router-link>

-5.路由模式如下
- hash 模式 (后面带#)
- history模式

6 编程式导航

1-1 声明式导航-单纯跳转路由页面

< router-link to=""></router-link>   里面带路径,加 /

1-2 编程式导航 router.push加传参

$router.push("search") //字符串
$router.push({path:"/search",query:{val:564}}); //对象传参是key,value的形式
$router.push({name:"search"})   //命名路由跳转
$router.replace({ path: "/search", query: { val: 156 } });
//动态路由-
$router.push({name:"shop",params:{id:id}}) //里面的id是可变的。
注意事项
1. query不传参也能跳转,query传参用path和name都可以
//----动态路由注意事项-------
2. params传参数必须用name跳转路由,params不传参不能跳转路由,
**** router和route的区别
console.log(this.$router);  //所有的路由信息
console.log(this.$route);  //当前的路由信息
嵌套路由
用children来配置父子路由 --------就是在当前页面路由下面配置子级children是个数组 children:[{}]
路由重定向 redirect

1.字符串的方式如下

routes: [
{ path: '/a', redirect: '/b' }
]
})   //在数组里面写对象,从路由/a重定向到路由/b

2.命名路由的方式

1.  const router = new VueRouter({
routes: [
{ path: '/a', redirect: { name: 'foo' }}
]
})

//也可以是个方法
2.const router = new VueRouter({
routes: [
{ path: '/a', redirect: to => {
// 方法接收 目标路由 作为参数
// return 重定向的 字符串路径/路径对象
}}
]
})
  • keep-alive 包裹动态组件是,会缓存不活动的组件实例,而不是销毁它们。
    例如:tab切换时,可以保存切换前的状态
<keep-alive></keep-alive>

导航守卫

  • 是在做权限验证的时候会使用导航守卫

组件内守卫

// 不能获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
//写在组件里面
beforeRouteEnter(to,from,next){
if(to.params.id<10) //如果数据里面的id小于10就表示有,就进入页面
next() 登录
}else{
next("/home")  返回首页
}
},

beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时触发
// 可以访问组件实例 `this`
next() 只要改变触发就执行next()
},

beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
next()
}
//to是要到哪里去
from是要从哪里来
next就是成功就执行

路由独享守卫

const router = new VueRouter({
routes: [
{
path: '/foo',
name:"foo"
component: Foo,

//它是在配置路由文件里面写 router/index.js
beforeEnter: (to, from, next) => {
// 只守卫当前的一条路由
}
}
]
})

全局守卫

const router = new VueRouter({
//里面是路由路径
})
const login=["order","my"]   //数组里面是要判断的路由的权限
router.beforeEach((to,from,next)=>{
if(login.includes(to.name)){  //权限
let userId=window.localStroage.getItem("userId") //只能存字符串
if(userId){  //登录
next()
}else{  //没有登录
next("/login")
}
}else
next()
})
export default router;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: