編程式路由傳參
除了使用 <router-link> 創(chuàng)建 a 標簽來定義導航鏈接绊袋,我們還可以借助 router 的實例方法,通過編寫代碼來實現(xiàn)额湘。
- 通過 params 傳遞
const routes = [
// 動態(tài)段以冒號開始
{ path: 'details/:id', name: "details", component: Details },
]
router.push() 方法的參數(shù)可以是一個字符串路徑七问,或者一個描述地址的對象。
const Home = {
template: '<div @click="toDetails">To Details</div>',
metheds: {
toDetails() {
// 字符串路徑
this.$router.push('/details/001')
// 帶有路徑的對象
this.$router.push({path: '/details/001'})
// 命名路由裆站,路由配置時,需要 name 字段
this.$router.push({ name: 'details', params: { id: '001' } })
}
}
}
注意黔夭,如果提供了 path宏胯,params 會被忽略:
// `params` 不能與 `path` 一起使用
router.push({ path: '/details', params: { id: '001' } }) // -> /details
組件獲取數(shù)據(jù)
當一個路由被匹配時,它的 params 的值將在每個組件中以 this.$route.params 的形式暴露出來本姥。
const Details = {
template: '<div>Details {{ $route.params.id }} </div>',
created() {
// 監(jiān)聽路由變化
this.$watch(
() => this.$route.params,
(toParams, previousParams) => {
// 對路由變化做出響應...
}
)
},
}
通過 query 傳遞
這種情況下 query (查詢參數(shù))傳遞的參數(shù)會顯示在 url 后面肩袍,如:/details/001?kind=car。
路由配置
使用 query 時婚惫,以下三種方式都是可行的:
1.this.$router.push('/details/001?kind=car')
2.this.$router.push({ path: '/details/001', query: { kind: "car" }})
3.this.$router.push({ name: 'details', params: { id: '001' }, query: { kind: 'car' }})
組件獲取數(shù)據(jù)
const Details = {
template: '<div>Details {{ $route.query.kind }} </div>',
created() {
// 監(jiān)聽路由變化
this.$watch(
() => this.$route.query,
(toParams, previousParams) => {
// 對路由變化做出響應...
}
)
},
}
要對同一個組件中參數(shù)的變化做出響應的話氛赐,你可以簡單地 watch route.query
通過 hash 傳遞(同query)組件通過 $route.hash.slice(1) 獲取
通過 props 進行傳遞
在組件中使用 $route 會與路由緊密耦合艰管,這限制了組件的靈活性,因為它只能用于特定的 URL蒋川。雖然這不一定是件壞事牲芋,但我>們可以通過 props 配置來解除這種行為。
對象模式
路由配置
const routes = [
{
path: '/hello',
component: Hello,
props: { name: 'World' }
}
]
組件中獲取數(shù)據(jù)
const Hello = {
props: {
name: {
type: String,
default: 'Vue'
}
},
template: '<div> Hello {{ name }}</div>'
}
<Hello /> 組件默認顯示 Hello Vue捺球,但路由配置了 props 對象缸浦,當路由跳轉到 /hello 時,會顯示傳遞過來的 name氮兵, 頁面會顯示為 Hello World裂逐。
其他方式
1. 通過 Vuex 進行傳遞
1. store 存儲狀態(tài);
2. A 組件更改 store 中的狀態(tài)泣栈;
3. B 組件從 store 中獲取卜高。
2.通過前端本地存儲等方式
1. Local Storage;
2. Session Storage;
3. IndexedDB;
4. Web SQL;
5. Cookies。
以上內(nèi)容僅供自己學習南片,查找方便