路由組件傳參
方式1:使用 $router.params
// 在路由中定義參數(shù)
const router = new VueRouter({
routes: [
{ path: '/user/:id', name: 'user', component: User }
]
})
// 頁(yè)面a跳轉(zhuǎn)的時(shí)候傳參
<router-link to="{ path:'/user/123'}">
或者
<router-link to="{ name: 'user', params: { id: 123 }}">User</router-link>
或者
this.$router.push({path: '/user/123'})
或者
this.$router.push({ name: 'user', params: { id: 123 }})
// 在 user 頁(yè)面中使用參數(shù)
<div>User {{ $route.params.id }}</div>
或者
this.$route.params.id
方式2: 使用props
文檔: https://router.vuejs.org/zh/guide/essentials/passing-props.html
在組件中使用 $route 會(huì)使之與其對(duì)應(yīng)路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用统阿,限制了其靈活性
使用 props 將組件和路由解耦:
// 定義路由 props
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User, props: true },
// 對(duì)于包含命名視圖的路由彩倚,你必須分別為每個(gè)命名視圖添加 `props` 選項(xiàng):
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
})
// 同方法1,在a頁(yè)面跳轉(zhuǎn)的時(shí)候傳參
<router-link to="{ path:'/user/123'}">
// 在路由user組件中使用props接受參數(shù)
const User = {
props: ['id'],
template: '<div>User {{ id }}</div>'
}
這樣你便可以在任何地方使用該組件扶平,可以路由使用帆离,也可以組件嵌套的時(shí)候使用,使得該組件更易于重用和測(cè)試结澄。
方式3: 通過(guò) vuex
雖然不太推薦哥谷,但是也可以通過(guò)vuex實(shí)現(xiàn),有點(diǎn)殺雞用牛刀
// 定義store
import Vuex from 'vuex'
import Vue from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
id: ''
},
mutations:{
setId(state , id) {
state.id = id
}
}
})
// 在a頁(yè)面設(shè)置
this.$store.commit( 'setId' 麻献,(123) )
// 在b頁(yè)面取
this.$store.state.id
方式4:使用本地存儲(chǔ)们妥,localstorage或者Session Storage
原理很簡(jiǎn)單,a頁(yè)面存勉吻,b頁(yè)面取监婶,不推薦
推薦方式2,解耦更通用