Vue路由模式有两种
如果不想要url中有#号,可以改为history模式
index.js
export default new Router({
mode: 'history',
routes: [
]
});
404 demo
1.创建一个NotFound.vue视图组件
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
}

beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
在Profile.vue中写
export default {
name: "UserProfile",
beforeRouteEnter: (to, from, next) => {
console.log("准备进入个人信息页");
next();
},
beforeRouteLeave: (to, from, next) => {
console.log("准备离开个人信息页");
next();
}
}
参数说明:
在钩子函数中使用异步请求
1.安装 Axios
根据官网

cnpm install --save vue-axios
3、准备数据 : 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。

{
"name": "冷丁",
"url": "https://blog.csdn.net/qq_41359998?spm=1011.2124.3001.5343",
"page": 1,
"address": {
"street": "海淀",
"city": "北京",
"country": "中国"
}
}
4.在 beforeRouteEnter 中进行异步请求
这里利用vm调用了下面的getData方法
Profile.vue
<template>
<div>
<h1>个人信息h1>
{$route.params.id}}-->
{{id}}
div>
template>
<script>
export default {
props:['id'],
name: "UserProfile",
beforeRouteEnter:(to,from,next)=>{
console.log("进入路由之前");
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>

拿到了json中的数据
