1、路由的安裝
- 首先安裝
npm install i vue-router --save
- 在main.js中引入,
我們一般把router相關的內容寫到一個單獨的router檔案夾中便于管理,然后再在main.js中引入這個檔案,
在new Vue時傳入
import router from './router'
,,,
new Vue({router ,,,,})
- router檔案夾的index.js檔案
引入,并用Vue.use注冊插件
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
定義路由routes 陣列
const routes = [
{
path: '/',
redirect: '/login'
},
,,,]
創建router實體
最后暴露出去,在main.js中引入,
const router = new VueRouter({
routes
})
export default router
在組件內使用留坑,
2、路由的跳轉
- 1、通過點擊router-link標簽
<router-link to='/goods'>
- 2、通過push方法
this.$router.push("/goods");
3、路由跳轉時的傳參
1、方法一
// 路由定義
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
// 頁面傳參
this.$router.push({
path: `/describe/${id}`,
})
// 頁面獲取
this.$route.params.id
2、方法二
// 路由定義
{
path: '/describe',
name: 'Describe',
omponent: Describe
}
// 頁面傳參
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
// 頁面獲取
this.$route.params.id
3、方法三
// 路由定義
{
path: '/describe',
name: 'Describe',
component: Describe
}
// 頁面傳參
this.$router.push({
path: '/describe',
query: {
id: id
`}
)
// 頁面獲取
this.$route.query.id
方法二引數不會拼接在路由后面,頁面重繪引數會丟失
方法一和三引數拼接在后面,丑,而且暴露了資訊,
4、$route和$router的區別
1、 $route是‘路由資訊物件’
包括path,params、hash、query、fullPath、matched、name等路由資訊引數
- path 當前路由的路徑
- params 路由引數
- query url查詢引數
- hash 當前路由的哈希值
- fullPath 當前路由的url,包含查詢引數和hash的完整路徑
- name 當前路由的名字
2、$router是路由實體物件
使用new VueRouter創建的實體,包含一些方法
-
this.$router.go(-1) 跳轉到上一頁
-
this.$router.push(’/menu’) 跳轉到指定路由
-
this.$router.push({name:‘menu’}) 通過名字跳轉
-
this.$router.replace(’/menu’)
-
this.$router.replace({name:‘menu’})
使用replace的話,不會添加一條新的記錄
5、導航守衛
導航守衛:通過跳轉時對跳轉給予放行還是不放行,實作對導航的守衛,
1、*全域前置守衛beforeEach
可以在專案內創建多個全域前置守衛
這個是常使用的
router.beforeEach((to,from,next)=>{
if(to.path==="/login"){
next();
return;
}
// 獲取token
const token=window.sessionStorage.getItem("token");
if(!token){
next('/login');
return;
}else{
next();
}
})
在守衛中,
- to 將要進入的目標路由物件
- from 當前正要離開的路由
- next 一定要呼叫next方法,
next(false)中斷當前的導航
2、全域后置鉤子afterEach
可以創建多個全域后置鉤子
不接受next函式,不會改變導航本身,
router.afterEach
3、beforeResolve全域決議守衛
可以創建多個
4、路由獨享守衛
不可以創建多個
卸載路由配置陣列項中,有next
5、beforeRouteEnter組件內的守衛
在組件內定義的路由導航守衛,(定義在created鉤子同級的位置)
beforeRouterEnter(to,from,next){
next((vm)=>{
})
},
是支持給next傳遞回呼的唯一守衛,回呼的引數是當前vue實體,
在beforeRouterEnter中,不可以使用this來訪問當前vue實體,
6、beforeRouteUpdate
在當前路由改變,但是該組件被復用時呼叫(嵌套組件的情況),在導航內可以訪問this
7、beforeRouteLeave
導航離開該組件的對應路由時呼叫
這個離開守衛可以用來禁止用戶在還未保存修改前離開,
該導航可以通過next(false)來取消導航,
6、命名路由
7、hash模式和history模式
1、hash模式
window物件提供了hashchange事件來監聽hash值的改變,一旦url中的hash值發生改變,便觸發該事件,
通過對location.hash賦值可以改變hash
2、history模式
HTML5中 History API提供,在不重繪整個頁面的情況下修改站點的url,window物件提供了popstate事件來監聽歷史堆疊的改變,一旦歷史堆疊的資訊發生改變,就觸發該事件,
但是呼叫history.pushState和history.replaceState方法不會觸發該事件,只有在做出瀏覽器動作時才觸發該事件,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/282347.html
標籤:區塊鏈
上一篇:關于以太坊的nonce值
下一篇:費馬小定理看了等于沒看證明
