vue-router路由導航
阿新 • • 發佈:2020-08-03
安裝路由
由於動態路由也是傳遞params的,所以在 this.$router.push() 方法中path不能和params一起使用,否則params將無效。需要用name來指定頁面。 通過name和params傳遞引數
this.$router.push({ name: ‘index’, params: { username: “fatjack”, password: 123 }}) 獲取
this.$route.params.username
this.$router.push({path: ‘/index’, query: { username: “fatjack”, password: 123 }}); 獲取
this.$route.query.username vue-router路由
npm install vue-router路由導航守衛
// to :是要去的哪個頁面 路由相關的引數 (表示 將要訪問的那個路由物件) // from :從哪個頁面即將離開 (從哪個路由物件,跳轉而來) // next :next 是一個函式,就相當於 Node 裡面 express 中的 next 函式 (代表放行) // next() 表示放行 next('/login') 表示強制跳轉到login頁 // 注意: 這裡的 router 就是 new VueRouter 得到的 路由物件 // 掛載路由導航守衛 router.beforeEach((to, from, next) => {去掉位址列的 # 號// 如果使用者輸入的是login頁面 直接放行 if (to.path === '/login') return next() // 檢視客戶端是否有token值 const tokenStr = window.sessionStorage.getItem('token') // 如果沒有token 則直接跳轉到登入頁 if (!tokenStr) return next('/login') // 有token放行 next() }) // 把路由導航暴露出去 export default router
const router = new VueRouter({ mode:路由傳參 父元件中: 使用 <router-link to="/需要跳轉的路徑/需要傳遞的引數"></router-link>'history', // 這樣就能去掉URL位址列的 # 號 routes })
// to屬性,表示 點選此連結,要跳轉到哪個 hash 地址 // tag 屬性 要渲染成什麼標籤 預設 是 a標籤 tag可以轉換成自己想要的標籤 <router-link to="/跳轉的地址/傳遞的引數" tag="li">首頁</router-link>子元件中是 this.$route.params.路由配置中的名稱 路由配置檔案
{ path: '子路由地址/:傳遞的引數', component: 子路由檔案 }this.$route包含的資訊
// fullpath 全地址 // path 路由地址 // params 路由的引數 // query 問號後查詢的引數 // name 路由名稱 // meta 路由元資訊,標識路由是否需要全域性守衛1.params
由於動態路由也是傳遞params的,所以在 this.$router.push() 方法中path不能和params一起使用,否則params將無效。需要用name來指定頁面。 通過name和params傳遞引數
this.$router.push({ name: ‘index’, params: { username: “fatjack”, password: 123 }}) 獲取
this.$route.params.username
<div>當前使用者名稱: {{this.$route.params.uaername}} </div>
2.query
通過path和query傳遞引數this.$router.push({path: ‘/index’, query: { username: “fatjack”, password: 123 }}); 獲取
this.$route.query.username vue-router路由