Vue(13)——路由模式,定制404及路由钩子的使用
1、路由模式
路由模式有两种:
- hash:路径带# 如http://localhost:8080/#/main (默认使用)
- history:路径不带# 如http://localhost:8080/main
修改路由模式为history;
export default new Router({
mode: 'history',
routes: [
]
});
2、定制404
1、定义一个名为NotFound的组件:
<template>
<div>
<h1>404页面找不到</h1>
</div>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
2、配置路由
import NotFound from "../view/NotFound";
{
path:'*',
component:NotFound
}
3、路由钩子
在路由跳转的时候,我们需要一些权限判断或者其他操作。这个时候就需要使用路由的钩子函数,也称路由钩子。
路由钩子:路由钩子主要是给使用者在路由发生变化(如页面跳转)时进行一些特殊的处理而定义的函数。
可以在组件内直接定义以下路由钩子:
- beforeRouteEnter:进入该组件的对应路由时调用
- beforeRouteLeave:离开该组件的对应路由时调用
测试路由钩子:
在Profile组件内进行测试
<script>
export default {
props: ['id','name'],
name: "UserProfile",
beforeRouteEnter:(to,from,next)=>{
console.log("进入该组件的对应路由时调用")
next();
},
//参数to, from, next
beforeRouteLeave:(to, from, next)=>{
console.log("离开该组件的对应路由时调用")
next();
}
}
</script>
访问页面测试
当我们进入Profile组件时:调用了beforeRouteEnter函数
当我们离开Profile组件,进入List组件时:调用了beforeRouteLeave函数
路由钩子参数说明:
- to: Route: 即将要进入的目标 路由对象
- from: Route: 当前导航正要离开的路由
- next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next方法的调用参数。
- next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。
- next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from` 路由对应的地址。
- next(’/’) 或者 next({ path: ‘/’ }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home’之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。
- next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
摘自vue-router文档:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E7%BB%84%E4%BB%B6%E5%86%85%E7%9A%84%E5%AE%88%E5%8D%AB
在钩子函数中使用异步请求
1、安装Axios和vue-axios
cnpm install axios -s
cnpm install --save vue-axios
2、main.js引入Axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
3、在项目的static目录下新建一个mock目录,把data.json文件放入mock目录
data.json:
{
"name": "狂神说java",
"url": "http://baidu.com",
"page": 1,
"isNonProfit":true,
"address": {
"street": "含光门",
"city":"陕西西安",
"country": "中国"
},
"links": [
{
"name": "B站",
"url": "https://www.bilibili.com/"
},
{
"name": 4399,
"url": "https://www.4399.com/"
},
{
"name": "百度",
"url": "https://www.baidu.com/"
}
]
}
4、编写异步请求
<template>
<div>
<h1>用户信息</h1>
{{id}}
{{name}}
</div>
</template>
<script>
export default {
props: ['id','name'],
name: "UserProfile",
beforeRouteEnter:(to,from,next)=>{
console.log("进入该组件的对应路由时调用");
//拿到实例vm
next(vm => {
vm.getData();
});
},
beforeRouteLeave:(to,from,next)=>{
console.log("离开该组件的对应路由时调用");
next();
},
methods: {
getData: function (){
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (response) {
console.log(response)
})
}
}
}
</script>
<style scoped>
</style>
5、打开控制台测试,
成功在进入Profile组件前,得到了data.json里的数据