前言
最近在寫Vue搭建的后臺管理系統(tǒng)逊躁,在跳轉(zhuǎn)頁面時(shí)想要保留地址欄參數(shù)谢翎,使刷新參數(shù)還在,但是不想顯示id:1,code:2的字段名id和code走趋,怎么辦呢衅金?
通常我們在兩個(gè)頁面?zhèn)鲾?shù)據(jù)時(shí),一般會(huì)采用params,query氮唯,或者將數(shù)據(jù)用vuex酥宴,localStorage,sessionStorage您觉,然后方便其他頁面調(diào)用數(shù)據(jù),但是params和vuex只要頁面刷新授滓,穿過來的數(shù)據(jù)就會(huì)丟失琳水,下面請看用params傳數(shù)據(jù)
方式一
{
path: '/operate',
component: Layout,
redirect: '/operate/banner',
name: 'Oprate',
meta: { title: '系統(tǒng)運(yùn)營', icon: 'el-icon-s-management' },
children: [
{
path: 'banner',
name: 'Banner',
component: () => import('@/views/operate/banner'),
meta: { title: 'Banner列表 ' },
children: [
{
// path:'/detail' // 這種方式不配置參數(shù)名, 頁面刷新會(huì)丟失參數(shù)
path: 'detail/:id', //這樣通過 name 和 params 進(jìn)行路由傳參時(shí)般堆,刷新頁面就不會(huì)丟失參數(shù)** id **了在孝。
name: 'BannerDetail',
component: () => import('@/views/operate/banner/detail'),
meta: { title: 'Banner詳情' },
hidden: true,
}
]
}
]
},
調(diào)整函數(shù):
// 詳情頁面
methods:{
detail(id) {
// this.$router.push('/BannerDetail')
this.$router.push({ name: "BannerDetail", params: { id: '111' } });
},
}
這樣傳參時(shí),地址欄就會(huì)出現(xiàn)參數(shù)了淮摔,這樣數(shù)據(jù)就不會(huì)丟失了私沮。
方式二
除此之外,我們還可以選擇配合 路由解耦 來使用
優(yōu)勢: 對路由參數(shù)的改變不需要通過 this.route和通過beforeRouteUpdate傳值時(shí)通過$route.params獲取參數(shù)改變時(shí)麻煩的寫法:
只適用于 params,不適用于query魔招;
實(shí)現(xiàn)方式:
在路由的配置項(xiàng)加一個(gè)props:true晰搀;
修改路由配置為:
children: [
{
//path:'/detail', // 這種方式不配置參數(shù)名, 頁面刷新會(huì)丟失參數(shù)
path: 'detail/:id', //這樣通過 name 和 params 進(jìn)行路由傳參時(shí)办斑,刷新頁面就不會(huì)丟失參數(shù)** id **了外恕。
name: 'BannerDetail',
component: () => import('@/views/operate/banner/detail'),
meta: { title: 'Banner詳情' },
hidden: true
props: true // 將需要傳的值寫在組件中 props 中。
}
]
要調(diào)整的組件中的props:
<script>
export default {
name: "BannerDetail",
props: {
//將路由中的參數(shù) id 解耦在組件上的 props 上乡翅。
id: {
type: String,
default: '',
required: true
}
},
}
</script>
<style scoped lang='scss'>
</style>
最后的效果 (刷新不會(huì)丟失):
好了鳞疲,今天要給大家分享的東西就這些了,有什么不明白的或者我寫的哪里需要完善的請留言告訴我呦~~~
當(dāng)然也可以通過 path 和 query 的方式進(jìn)行傳參 this.$router.push({path: 路由路徑蠕蚜,query: {要傳的產(chǎn)生} })
但是這不能進(jìn)行 props 解耦尚洽。