路由模式
两种路由模式
hash
: 路径带#
,如http://localhost:8080/#/main
history
: 路径不带#
,如http://localhost:8080/main
修改路由配置
export default new Router({
mode: 'history',
routes: [
]
})
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
}
只要不符合前面的路由配置路径,就跳转到NotFound
组件,404页面
路由钩子
beforeRouteEnter
进入路由之前执行
beforeRouteLeave
离开路由之前执行
<script>
export default {
// 在props中设置路由的参数
props: ['id'],
name: "UserProfile",
beforeRouteEnter(to,from,next)=>{
// 不能获取组件实例 this 因为当守卫执行前,组件实例还没被创建
console.log("进入路由之前");
next();
},
beforeRouteLeave(to, from, next) {
// 离开该组件的对应路由时调用 可以访问组件实例 this
console.log("离开路由之前");
}
}
</script>
参数
to
: 即将要进入的目标(路由对象)from
: 当前导航正要离开的路由next
: 路由的控制参数,一定要调用这个方法next()
: 进入下一个钩子,如果钩子都执行完了,就进入页面next(false)
: 返回之前的页间next('newpath')
或者next({ path: 'newpath' })
: 改变路由的跳转放行,跳转到newpath
路由next((vm)=>{})
: 只能在beforeRouteEnter
钩子使用,vm
是组件实例
beforeRouteEnter
进入路由之前获取数据
# 安装 axios vue-axios 依赖
npm install --save axios vue-axios
index.js 中添加依赖并安装 axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios);
static
下新建文件夹mock
,创建json数据 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/"
}
]
}
Profile.vue 中添加方法
export default {
// 在props中设置路由的参数
props: ['id'],
name: "UserProfile",
beforeRouteEnter: (to,from,next)=>{
// 不能获取组件实例 this 因为当守卫执行前,组件实例还没被创建
next(vm => {
// 在进入路由之前,调用vm实例的getData方法获取数据
vm.getData();
});
console.log("进入路由之前");
next();
}
}
methods: {
// 使用axios获取数据
getData: function () {
this.axios({
method: 'get',
url: 'http://localhost:8080/static/mock/data.json'
}).then(resp=>{
console.log(resp.data)}
)
}
}
点击个人信息会触发钩子函数,获取数据
项目结构