環境搭建
路由模式
兩種路由模式
hash: 路徑帶#,如http://localhost:8080/#/mainhistory: 路徑不帶#,如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)}
)
}
}
點擊個人資訊會觸發鉤子函式,獲取資料

專案結構

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/278819.html
標籤:其他
