1.1、路由模式有两种:
修改路由配置,代码如下:
效果:
1.2、处理404创建一个名为NotFound.vue的视图组件:
<template>
<h1>404,你的页面走丢了</h1>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
修改路由配置:
import NotFound from '../views/NotFound'
{
path:'*',
component: NotFound
}
效果:
beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
沿用上一篇博客“参数传递及重定向”项目!
修改Profile.vue:
<template>
<div>
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
props: ['id'],
name: "UserProfile",
beforeRouteEnter:(to,from,next) => {
console.log("进入路由之前");
next();
},
beforeRouteLeave:(to,from,next) => {
console.log("离开路由之前");
next();
}
}
</script>
<style scoped>
</style>
效果:
参数说明:
在钩子函数中使用异步请求
1、安装Axios cnpm install axios -s
2、main.js引用Axios
3、在上述基础上,增加功能,实现在进入Profile.vue之前,完成数据的加载
新建static/mock/data.json:
{
"name":"马西莫",
"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、修改Profile.vue:
<template>
<div>
<h1>个人信息</h1>
{{id}}
</div>
</template>
<script>
export default {
props: ['id'],
name: "UserProfile",
beforeRouteEnter:(to,from,next) => {
console.log("进入路由之前");//加载数据
next(vm => {
vm.getData();//进入路由之前执行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>
运行效果: