[vue]404和路由钩子
404和路由钩子
- index.js中的export default new Router 下写入 mode: 'history',可以去除链接中的#
新建一个NotFound.vue
<template>
<div>
<h1>404!页面找不到</h1>
</div>
</template>
<script>
export default {
name: "NotFound"
}
</script>
<style scoped>
</style>
index.js中导入,写入router
import NotFound from '../views/NotFound'
{
path: '/*',
component: NotFound
},
安装axios
npm install axios -s
在main.js中导入
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Profile.vue
<script>
export default {
props: ['id'],
name: "Profile",
//进入路由前
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>
参数说明:
- to:路由将要跳转的路径信息
- from:路径跳转前的路径信息
- next:路由的控制参数
- next() 跳入下一个页面
- next('/path') 改变路由的跳转方向,使其跳到另一个路由
- next(false) 返回原来的页面
- next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例