zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    Jackrabbit 中Session最佳实践
    Android 学习历程
    SmartFoxServer 学习笔记 002
    互联网的下一代
    VirtualBox 中 安装 Ubuntu Desktop 10 桌面分辨率的调整
    学习 SmartFoxServer 笔记 001
    手工转换中缀式与前、后缀式
    汉字传值奇数乱码问题解决策略
    git权限管理工具gitolite使用笔记(一)
    git 安装笔记
  • 原文地址:https://www.cnblogs.com/hthuang/p/7646472.html
Copyright © 2011-2022 走看看