目录
1、路由模式
路由模式有两种
- hash:路径带 # 符号,如 http://localhost/#/login
- history:路径不带 # 符号,如 http://localhost/login
修改路由配置
export default new VueRouter({
mode:'history',
routes: []
)}
在路由的配置中修改
2、404页面
(1)创建一个NotFound.vue视图
<template>
<div>
<h1>404,你的页面走丢了</h1>
</div>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
(2)修改路由配置index.js
import NotFound from '../views/NotFound'
{
path: '*',
component: NotFound
}
(3)测试
3、路由钩子
除了之前的钩子函数还存在两个钩子函数
- beforeRouteEnter:在进入路由前执行
- beforeRouteLeave:在离开路由前执行
在 Profile.vue 使用
<script>
export default {
name: "UserProfile",
beforeRouteEnter: (to, from, next) => {
console.log("准备进入个人信息页");
next();
},
beforeRouteLeave: (to, from, next) => {
console.log("准备离开个人信息页");
next();
}
}
</script>
参数说明:
- to:路由将要跳转的路径信息
- from:路径跳转前的路径信息
- next:路由的控制参数
- next(): 跳入下一个页面
- next(’/path’) :改变路由的跳转方向,使其跳到另一个路由
- next(false) :返回原来的页面
- next((vm)=>{}): 仅在 beforeRouteEnter 中可用,vm 是组件实例
在钩子函数中进行异步请求
(1)安装Axios
cnpm install --save vue-axios
(2)main.js引用 Axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
(3)准备数据
{
"name": "cv战士",
"url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343",
"page": 1,
"isNonProfit": true,
"address": {
"street": "含光门",
"city": "陕西西安",
"country": "中国"
},
"links": [
{
"name": "bilibili",
"url": "https://bilibili.com"
},
{
"name": "cv战士",
"url": "https://blog.csdn.net/qq_45408390?spm=1001.2101.3001.5343"
},
{
"name": "百度",
"url": "https://www.baidu.com/"
}
]
}
说明: 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下
在 beforeRouteEnter 中进行异步请求
<script>
export default {
name: "UserProfile",
beforeRouteEnter: (to, from, next) => {
console.log("准备进入个人信息页");
next(vm => {
//进入路由之前执行getData方法
vm.getData()
});
},
beforeRouteLeave: (to, from, next) => {
console.log("准备离开个人信息页");
next();
},
//axios
methods: {
getData: function () {
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(function (response) {
console.log(response)
})
}
}
}
</script>
测试