hash地址与组件之间的对应关系
前端路由的工作方式:
vue-router官网
目前最新 npm install vue-router@4
vue2适用 npm install [email protected] -S
在src目录下,新建router/index.js路由模块,内容如下:
//1、导入vue和vueRouter
import Vue from 'vue'
import VueRouter from 'vue-router'
//2、使用路由
Vue.use(VueRouter)
//3、构造路由实例对象
const router = new VueRouter()
//4、把实例对象导出,共享一个路由对象
export default router
在main.js中挂载
import router from '@/router/index.js'
//可以简化,不写index.js,因为引入的是文件夹,会自动找到文件夹下的index.js
new Vue({
render: h => h(App),
//路由挂载
router
}).$mount('#app')
import Left from '@/components/Left.vue'
import Right from '@/components/Right.vue'
//3、构造路由实例对象
const router = new VueRouter({
routes: [
{ path: "/left", component: Left },
{ path: "/right", component: Right }
]
})
//然后在要使用的地方写上占位符
左侧
右侧
{ path: "/", redirect: "/left" },
加上children
//3、构造路由实例对象
const router = new VueRouter({
routes: [
{ path: "/", redirect: "/left" },
{ path: "/left", component: Left },
{
path: "/right",
component: Right,
redirect:"/right/tab1"
children: [
{ path: "tab1", component: Tabone },
{ path: "tab2", component: Tabtwo }
]
}
]
})
把hash地址中可变部分定义为参数项,从而提高路由规则的复用性
{ path: "/movie/:id", component: Movie}
为路由规则开启props传参
{ path: "/movie/:id", component: Movie, props:true}
在使用的组件中
{{id}}
export default {
props:['id']
}
声明式:点击链接,例如、
编程式:调用API方法实现跳转,例如push、replace、go三种方法
//跳转,增加一条历史记录
this.$router.push("/left")
//跳转,替换当前历史记录
this.$router.replace("/left")
//在历史记录中前进或者后退,一般只前进或者后退一步,所以提供了back、forward代表前进或后退一步
this.$router.go(-1)
this.$router.back()
this.$router.forward()
导航守卫可以控制路由的访问权限
一般用于检测登录权限
//只要发生路由跳转,必然触发before指定的回调函数
router.beforeEach(function(to,from,next){
//to将要访问的路由对象信息
//from表示要离开的对象信息
//next函数表示放行
next()
})
控制访问权限例子:
//只要发生路由跳转,必然触发before指定的回调函数
router.beforeEach(function(to,from,next){
if(to.path === '/main'){
const token = localStorage.getItem('token')
if(token){
next()//有token值则直接访问后台主页
} else{
next('/login')//没有token,则跳转到登录页
}
}else{//不是访问后台主页,则直接放行
next()
}
})