一、vue-router的基本使用
1、安装vue-router,创建router文件夹并新建index.js文件,基本结构如下:
//导入
import Vue from "vue"
import Router from "vue-router"
import Home from "../components/Home.vue"
//使用该插件
Vue.use(Router)
//创建一个路由实例
const routes = [
{
//重定向设置默认路径
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
}
]
const router = new Router({
routes,
//默认设置为hash模式,可修改为history模式
mode:"history"
})
//导出
export default router
2、在main.js中导入,并挂载到Vue实例当中去
import router from "./router"
new Vue({
router,
render: h => h(App),
}).$mount('#app')
二、router-link相关
1、在App.vue的模板中写入router-link可实现路由跳转,并通过router-view来显示对应内容
<router-link to="/home">首页</router-link>
<router-view></router-view>
2、router-link标签默认被渲染为a标签,可通过tag属性修改为button
<router-link to="/home" tag="button">首页</router-link>
3、点击某个router-link后会自动添加router-link-active的class,我们可以修改该类来设置css样式
.router-link-active {
color: #f00;
}
三、通过js代码进行路由跳转
1、通过点击按钮来进行路由跳转
//在模板中新增一个button
<button @click="homeClick">首页</button>
//在脚本中的methods属性中增加该方法
homeClick() {
this.$router.push("/home")
}
2、但是这样做的话,如果重复点击该按钮会报错:Unhandled promise rejection Error: Avoided redundant navigation to current location: “/home”.希望我们不要重复地导航到当前地址,解决办法很多,这里提供一种:
//检查当前路径的值,若相同则刷新,否则就跳转
homeClick() {
if(this.$router.currentRoute.fullPath=="/home"){
this.$router.go(0);
}else {
this.$router.push("/home")
}
},
四、动态路由
1、在path后添加我们希望携带的参数,此处的userid为变量
{
path:'/user/:userid',
component:User
}
2、在data中传入id的值之后在router-link中使用
<router-link :to="'/user/'+id">用户</router-link>
五、路由的懒加载
1、为了解决webpack打包后文件过大,从而导致首页加载时间过长,我们需要使用路由的懒加载,即使用的时候再进行加载,使用如下:
// import Home from "../components/Home.vue"
const Home = () => import("../components/Home.vue")
六、路由的嵌套
1、创建两个组件HomeNews.vue和HomeMessage.vue
2、使用懒加载
const HomeNews = () => import("../components/HomeNews.vue")
const HomeMessage = () => import("../components/HomeMessage.vue")
3、增加children属性,注意在子路径前不需要加斜杠
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:HomeNews
},
{
path:'message',
component:HomeMessage
}
]
},
4、在Home.vue中增加router-link和router-view,这里需要写绝对路径
<router-link to="/home/news">新闻</router-link>
<router-link to="/home/message">消息</router-link>
<router-view></router-view>
5、设置默认路径,注意这里也不需要加斜杠
{
path:'',
redirect:'news'
},
七、参数传递(query形式)
1、url的组成:协议+域名+端口+路径+查询+片段,例如百度翻译:
2、使用query传参
<router-link :to="{path:'/profile', query:{name:'wsh', sex:'male', age:19}}">档案</router-link>
url:
3、通过$route.query的方式可以取出
<p>{{$route.query.name}}</p>
<p>{{$route.query.sex}}</p>
<p>{{$route.query.age}}</p>
八、导航守卫
1、在router文件夹的index.js文件中router实例后定义beforeEach的为全局前置守卫,
① to: Route: 即将要进入的目标 路由对象
② from: Route: 当前导航正要离开的路由
③ next: Function: 一定要调用该方法来 resolve 这个钩子。
在每个route中定义name属性,可做到每次路由跳转后更改标题:
router.beforeEach((to,from,next) => {
document.title = to.name
next()
})
2、在router文件夹的index.js文件中router实例后定义afterEach的为全局后置钩子,
router.afterEach((to,from) => {
//some codes
})
3、路由独享的守卫beforeEnter
4、组件内的守卫beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave
详情可见官网