vue路由传参的五种基本方式
方案一:
直接调用$router.push 实现携带参数的跳转
getDescribe(id) {
this.$router.push({
path: `/describe/${id}`,
})
需要对应路由配置如下:
{
path: '/describe/:id',
name: 'Describe',
component: Describe
}
很显然,需要在path中添加/:id来对应 $router.push 中path携带的参数。在子组件中可以使用来获取传递的参数值。
this.$route.params.id
方案二:
父组件中:通过路由属性中的name来确定匹配的路由,通过params来传递参数。
this.$router.push({
name: 'Describe',
params: {
id: id
}
})
对应路由配置: 这里可以添加:/id 也可以不添加,不添加数据会在url后面显示,不添加数据就不会显示
{
path: '/describe',
name: 'Describe',
component: Describe
}
子组件中: 这样来获取参数
this.$route.params.id
方案三:
父组件:使用path来匹配路由,然后通过query来传递参数
这种情况下 query传递的参数会显示在url后面?id=?
this.$router.push({
path: '/describe',
query: {
id: id
}
})
对应路由配置:
{
path: '/describe',
name: 'Describe',
component: Describe
}
对应子组件: 这样来获取参数
this.$route.query.id
方案四、还有一种就是使用vuex
在App.vue中,created初始化生命周期中写入以下方法
//在页面刷新时将vuex里的信息保存到localStorage里
window.addEventListener("beforeunload",()=>{
localStorage.setItem("messageStore",JSON.stringify(this.$store.state))
})
//在页面加载时读取localStorage里的状态信息
localStorage.getItem("messageStore") && this.$store.replaceState(Object.assign(this.$store.state,JSON.parse(localStorage.getItem("messageStore"))));
replaceState这个方法呢,查了api,就是替换 store 的根状态,然后通过对象赋值assign将localStorage进行赋值
beforeunload这个方法是在页面刷新时触发的,将store中的信息存入localStorage
这样就通过localStorage来避免vuex刷新数据消失的问题了。
方案五、简单粗暴的方式直接使用localStorage
以上是路由传参和vuex存值、传值的时候刷新页面数据消失的解决办法。