• vue前端页面跳转参数传递及存储


    不同页面间进行参数传递,实现方式有很多种,最简单最直接的方式就是在页面跳转时通过路由传递参数,如下所示。

    路由传递参数

    this.$router.push({
    	name: '跳入页面',
    	params: {
    		pid: pid,
    	}
    })
    

    实现方式如上所示,利用router.push方法可以从当前页面跳入指定的页面,跳入的页面通过name属性来确定。name属性里面的内容是在路由routes中定义的。如下所示:

    const routes = [{
      path: '/login',
      component: Login,
      name: '跳入页面'
    }]
    

    参数通过params属性来传递,如上例中传递了一个pid的参数给页面Login。

    路由传递参数好处是简单方便、不占用系统内存。但有个缺点是无法保存传递过来的参数,当刷新页面后,参数遗失。

    vuex传递数据

    vuex是一个专为Vue.js应用程序开发的状态管理模式,采用集中式存储管理应用的所有组件的状态。在使用vuex之前需要安装,index.js引入vuex代码如下:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    import store from './vuex/store'
    
    Vue.use(Vuex)
    
    new Vue({
      el: '#app',
      router,
      store,
      template: '<App/>',
      components: { App },
    })
    

    其中import store from './vuex/store'是引入store.vue文件,里面配置的是vuex存储信息,如下所示:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    const store = new Vuex.Store({
      state: {
        reportId: null,
        reportType: null
      },
      mutations: {
        SET_ReportId (state, rid) {
          state.reportId = rid;
        },
        SET_ReportType (state, type) {
          state.reportType = type;
        }
      }
    })
    
    export default store
    

    其中,state中reportId、reportType是要传递的参数;mutations中定义的传入参数时的方法。store.vue相当于是一个容器,定义了元素、存储元素的方法。那么如何使用呢?如何调用存储方法呢?调用方法如下:

    this.$store.commit('SET_ReportId', "10010");
    

    使用方法如下:

    this.rid = this.$store.state.reportId;
    

    使用vuex的好处是不一定非得向跳入页面传递参数,也可向上级页面传递参数或者跨组件传递参数。但缺点是当刷新页面时,无法继续加载传递的参数。

    在刷新页面时,路由和vuex都不能保存提取参数。如果想要在刷新页面时仍然提取之前的参数,到底有没有办法实现呢?答案是有,这是我们可以通过localStorage实现。

    localStorage传递参数

    localStorage是将参数存储在本地,当刷新页面时,从本地提取参数。localStorage传递参数比较简单,参数存储方式如下:

    window.localStorage.setItem('reportId', rid);
    

    参数提取方法如下:

    this.rid = window.localStorage.getItem('reportId');
    

    参考博主个人博客:http://www.ygingko.top/2017/09/16/vue-problem-PassingParaBetweenPage/

  • 相关阅读:
    如何阅读大型项目的代码?
    常用法律常识链接
    ubuntu 常用参数设置
    访问内存过程小结
    Netfilter深度解剖
    linux中的namespace
    style="display:none"隐藏html的标签
    xshell用ssh连接VMware中的ubuntu
    rails rake和示例
    rails中render 和 redirect_to的区别, each只能用在数组中,如果只有一个或者零个项,用each方法会报错undefined method `each' for #...
  • 原文地址:https://www.cnblogs.com/hthuang/p/7646472.html
Copyright © 2020-2023  润新知