vue返回上一页带参数
时间: 2025-02-18 10:06:46 浏览: 60
### Vue.js 中实现返回上一页并携带参数
在 Vue.js 应用程序中,可以利用 `vue-router` 提供的导航功能来实现返回上一页的同时传递参数。这通常涉及到使用编程式的导航以及存储临时状态。
#### 使用 Vuex 存储参数
为了确保参数可以在不同页面之间共享而不丢失,在离开当前页之前可将所需参数保存到 Vuex store 中[^3]:
```javascript
// 在准备跳转前保存参数至 Vuex Store
this.$store.commit('setReturnParams', params);
```
随后,在目标页面加载完成后读取这些参数,并执行必要的操作或将其作为查询字符串附加给 URL。
#### 编程式导航与历史记录管理
借助于 vue-router 的实例方法 `$router.go(-1)` 可以方便地让浏览器回退至上一浏览位置;而要附带额外的信息,则需考虑采用如下策略之一:
- **URL 查询参数**:修改即将访问的历史条目中的 query 属性;
```javascript
const queryParams = { key: value };
this.$router.push({ path: '/', query: Object.assign({}, this.$route.query, queryParams)});
```
- **本地存储(Local Storage)** 或者 SessionStorage :对于不想暴露在地址栏里的敏感信息来说是个不错的选择。
```javascript
sessionStorage.setItem('returnData', JSON.stringify(params));
this.$router.back();
```
一旦回到之前的页面,就可以从相应的源恢复数据了。
#### 完整示例代码展示
下面给出一段完整的 JavaScript (ES6+) 示例代码片段,展示了如何结合上述两种方式完成带有参数的页面回溯过程:
```javascript
// main.js 初始化 Vuex 和 Router...
import Vue from 'vue';
import App from './App.vue';
import router from './router'; // 导入路由配置文件
import store from './store'; // 导入 Vuex Store 配置文件
new Vue({
el: '#app',
router,
store,
render: h => h(App),
});
// componentA.vue 发送端组件
<template>
<div class="container">
<!-- ... -->
<button @click="goBackWithParam">Go Back With Param</button>
</div>
</template>
<script>
export default {
name: "ComponentA",
methods:{
goBackWithParam(){
let paramToPass = {'message': 'Hello'};
// 方法一:通过 URL Query 参数传送
this.$router.replace({...this.$route.query,paramToPass});
this.$router.go(-1);
/*
* OR 方法二:通过 Local/Session Storage 传送更私密的数据
*/
/*
sessionStorage.setItem('paramKey','value');
this.$router.back();
*/
}
}
}
</script>
// componentB.vue 接收端组件
<template>
<div class="container">
{{receivedMessage}}
</div>
</template>
<script>
export default {
computed: {
receivedMessage () {
return this.$route.query.message || '';
},
// 如果选择了第二种方案则改为:
/*
receivedMessage() {
return sessionStorage.getItem('paramKey') || '';
}*/
},
watch: {
'$route'(to,from){
console.log(`Navigated to ${to.path} from ${from.path}`);
}
}
}
</script>
```
阅读全文
相关推荐

















