(梳理復(fù)習(xí),很基礎(chǔ)很簡(jiǎn)略,學(xué)習(xí)vue-router推薦去看官方文檔)
文檔參考: Vue Router
1.路由概念(感覺還很模糊)
路由——url的分層解析隶债。(確定端與端的通信路徑)
第一層 解析到服務(wù)器目標(biāo)機(jī)器饺汹。這個(gè)通常是域名或ip宅静。
第二層 解析到服務(wù)器的特定資源文件高每。這個(gè)通常是pathinfo屿岂。
第三層 解析特定資源的特定狀態(tài)。包含在pathinfo參數(shù)中鲸匿。
主要是服務(wù)器爷怀,資源文件,特定狀態(tài)定位带欢。
在vue中运授,路由 確定url與路由組件間的通信路徑(一種映射),且可數(shù)據(jù)交互
2.安裝和基本使用
安裝
npm i vue-router -S
使用
// 1.引用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 2.創(chuàng)建路由實(shí)例
export default new VueRouter({
routes: [ // 3.配置 routes
{ path: '/a', component:A } // 配置之前需創(chuàng)建路由組件 A.vue
]乔煞,
linkActiveClass: 'myActiveClass', //設(shè)置 <router-link> 激活后 的 類名
})
// 4.在main.js 的 Vue實(shí)例 中注冊(cè)路由
import Vue from 'Vue'
import router from './router/index.js' // ./router/index.js(路由文件路徑)
export default new Vue({
el: '#app',
router // 注冊(cè)路由器
})
// 5.通過HTML標(biāo)簽展示
<!-- 路由鏈接 -->
<router-link to="path1">路由1</router-link>
<router-link to="path2">路由2</router-link>
<router-view></router-view> <!-- 路由容器 -->
3.路由的嵌套
在 routes 中
routes: [
{
path: '/parent',
component: Parent,
alias: '/p', // 路徑別名
children: [ // 嵌套的子路由
{path: '/parent/son1', component: Son1} // path的一種方式
{path: 'son2', component: Son2} // path的另一種方式
]
}
]
4.向路由組件傳輸數(shù)據(jù)
數(shù)據(jù) 從 路由器模塊(index.js) 吁朦, 傳輸?shù)铰酚山M件
$route"當(dāng)前路由
1.獲取參數(shù)方式 2.<router-link to="/a"> 3.{path: '/a', component: A}
通過$route.query --- to="/a?id=參數(shù)'&name=參數(shù)'" --- path: '/a'
通過$route.params --- to="/a/id的參數(shù)/name的參數(shù)'' --- path: '/a/:id/:name' (占位符)
注:參數(shù)為變量 to="..." 需改變(用 : 綁定to) :to=`/a?id=${變量}` :to=`/a/${變量}`
5.編程式的路由導(dǎo)航
借助 router 的方法router.push(...)
來實(shí)現(xiàn)路由導(dǎo)航,來代替 聲明式 <router-link :to="...">
的導(dǎo)航
編程式: 意思通過編寫JS代碼(實(shí)現(xiàn)功能)
router.push() 方法
// 字符串
router.push('a')
// 對(duì)象
router.push({ path: '/a' })
// 命名的路由
router.push({ name: '/a', pramas: { id: 123 }}) // -> /a/123
// 帶參數(shù)
router.push({ path: '/a', query: { id: 123 }}) //->/a?id=123
在 Vue 實(shí)例內(nèi)部,通過this.$router
訪問路由實(shí)例
編程式 聲明式 能否回退(向 history 添加新記錄)
this$router.push(...) <router-link :to="..."> 能(添加)
this$router.replace(...) <router-link :to="..." replace> 不能(不添加)
回退
this.$router.back()
this.$router.go(-1)
前進(jìn)
this.$router.go(1)