vue this.$router.go(-1);返回时如何带参数
作者:Rainbow_Xjj
这篇文章主要介绍了vue this.$router.go(-1);返回时如何带参数问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue this.$router.go(-1);返回时如何带参数
1. 声明一个空的Vue模块eventBus
import Vue from 'vue'
/**
* 定义空的vue实例,作为 eventbus实现非父子组件之间的通信(vue2.x中去掉了broadcast)
*/
var eventBus = new Vue({});
export default eventBus;2.“列表页”通过eventBus.$emit传参给上一个页面
import eventBus from '../../../static/js/eventbus.js';
//返回
back(info){
//传递一个map,addressInfo是key,info是value
eventBus.$emit('addressInfo',info);
//调用router回退页面
this.$router.go(-1);
},3. 页面接收参数
import eventBus from '../../../static/js/eventbus.js';
activated(){
//根据key名获取传递回来的参数,data就是map
eventBus.$on('addressInfo', function(data){
console.log(data,"data");
}.bind(this));
},vue $router.go(-1)的使用
在项目中可能会遇到这样的问题,就是跳到详情在返回来还希望保持原来的搜索结果,就是不希望刷新,这个时候呢keep-alive就起到了很大的作用
接下来就说说如何使用keep-alive来动态缓存页面的。
直接在外边加一层keep-alive就是全部缓存,返回都不刷新
比如在App.vue
<template>
<div id="app">
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</template>配合路由使用,动态去缓存你所需要缓存的,而不是全部缓存
需要在router.js里边配置
const router = new Router({
// mode: 'history',
routes: [{
path: '/', // 这个斜杠就是默认跳转的页面
name: 'index',
component: resolve => require(['@/components/index'], resolve),
meta: {
requiresAuth: true,
keepAlive: false,
}
},
{
path: '/index',
name: 'index',
component: resolve => require(['@/components/index'], resolve),
meta: {
requiresAuth: true, //设置此项则表示必须登录才能进入
keepAlive: false, //若为false则初始不缓存,若为true则表示缓存
}
},
{
path: '/index2',
name: 'index2',
component: resolve => require(['@/components/index2'], resolve),
meta: {
requiresAuth: true
}
}]
})然后在路由导航守卫去做权限处理
我是写在route/index.js中,这个看你不要求
// 判断是否需要登录权限 以及是否登录
router.beforeEach((to, from, next) => {
if (to.path == '/orderDs' || to.path == '/interveneDs' || to.path == '/afterSaleDs' || to.path == '/checkDs' || to.path == '/auditDs' || to.path == '/addVertising' || to.path == '/buyerDs' || to.path == '/gsQueryDs') {
from.meta.keepAlive = true; // from.meta 表示缓存列表页
next();
}else{
from.meta.keepAlive = false;
next();
}
})
export default router接下来看看在app.vue中的处理
<template>
<div id="app">
需要缓存的
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
不需要缓存的
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
</template>当我们使用缓存的时候
如果遇到我们界面做了一些操作,然后跳转回来需要把一些数据默认为原本的值
可以使用watch来监听$router
watch:{
$router:{
handler(val){
if(val.name==='menberList'){
this.getTableData()
}
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
