当前位置:   article > 正文

vue返回上一页并传递参数_vue返回上一页带参数

vue返回上一页带参数

需求:从A页面跳转到B页面,从B页面再返回至A页面,并传递参数。

1、使用sessionStorage或者localStorage

B页面返回之前将数据放置在sessionStorage里面

sessionStorage.setItem('searchKeyword', JSON.stringify({ fundname: '易方达基金', fundcode: '110011' }))
this.$router.go(-1)
  • 1
  • 2

返回到上一个页面之后,A页面拿到数据,再清空sessionStorage

const searchKeyword = JSON.parse(sessionStorage.getItem('searchKeyword'))
if (searchKeyword) {
	sessionStorage.removeItem('searchKeyword')
}
  • 1
  • 2
  • 3
  • 4

2、beforeRouteLeave和beforeRouteEnter

B页面设置beforeRouteLeave,代码如下:

beforeRouteLeave (to, from, next) {
    to.query.fundname = '易方达基金'
    to.query.fundcode = '110011'
    next()
}
  • 1
  • 2
  • 3
  • 4
  • 5

A页面设置beforeRouteEnter,代码如下:

export default {
	data () {
    	return {
    		fundname: '',
    		fundcode: ''
    	}
    },
    beforeRouteEnter (to, from, next) {
    	next(vm => {
        	vm.fundname = to.query.fundname
        	vm.fundcode = to.query.fundcode
      	})
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

3、vuex传值

  1. store文件配置
export default new Vuex.Store({
  state: {
    searchKeyword: {}
  },
  getters: {
    searchKeyword: state => state.searchKeyword
  },
  mutations: {
    SET_KEYWORD (state, payload) {
      state.searchKeyword = payload
    }
  },
  actions: {
    setKeyword ({ commit }, value = {}) {
      commit('SET_KEYWORD', value)
    }
  }
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  1. B页面组件使用
this.$store.dispatch('setKeyword', JSON.stringify({ fundname: '易方达基金', fundcode: '110011' }))
  • 1
  1. A页面组件使用
computed: {
    ...mapGetters({
      searchKeyword: 'searchKeyword'
    })
}
  • 1
  • 2
  • 3
  • 4
  • 5

4、EventBus使用

EventBus 是一种用于实现发布-订阅模式的开源事件总线库。它可以用于在应用程序中不同组件之间进行解耦的事件通信。通过注册和发布事件,不同的组件可以订阅感兴趣的事件并在事件发生时接收通知。这种方式可以简化组件之间的通信和协作,提高代码的可维护性和可扩展性。在 Android 开发中,EventBus 经常被用来简化组件之间的通信。

用法:

  1. 在main.js中全局初始化EventBus
Vue.prototype.$EventBus = new Vue()
  • 1
  1. 在B页面组件中向EventBus发送事件
this.$EventBus.$emit('searchKeyword', JSON.stringify({ fundname: '易方达基金', fundcode: '110011' }))
this.$router.go(-1)
  • 1
  • 2
  1. 在A页面组件中接收事件
mounted () {
    this.$EventBus.$on('searchKeyword', (data) => {
      console.log(data)
    })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 移除监听
beforeDestroy () {
    this.$EventBus.$off('searchKeyword')
}
  • 1
  • 2
  • 3
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/824632
推荐阅读
相关标签
  

闽ICP备14008679号