Vue Route Params 传参 实现刷新也会保留数据

1,020 阅读1分钟

1.为什么使用 vue route的 params传参

vue的传参

  • 动态路径参数 以冒号开头

    const router = new VueRouter({
      routes: [
        // 动态路径参数 以冒号开头
        { path: '/user/:id', component: User }
      ]
    })
    // 组件内使用获取
    console.log(this.$route.params.id)
    
  • query 传参

    const router = new VueRouter({
      routes: [
        // 动态路径参数 以冒号开头
        { path: '/user', component: User, name: 'user' }
      ]
    })
    // 通过路由属性中的path,匹配组件/user?id=id 组件内通过 this.$route.query 获取参数
    this.$router.push({
        path: '/user',
        query: {
            id: id
        }
    })
    
  • params 传参

    const router = new VueRouter({
      routes: [
        // 动态路径参数 以冒号开头
        { path: '/user', component: User, name: 'user' }
      ]
    })
    // 组件中,通过路由属性中的name来确定匹配的路由,通过params来传递参数。
    this.$router.push({
        name: 'user', // 注意:params 传参只能使用命名路由name跳转
        params: {
            id: id
        }
    })
    // 通过this.$route.params 获取参数
    

params传参的优缺点

  • 优点

    • 不会显示在地址栏上,会保存在内存中
    • 参数长度不需要考虑会不会太长问题
  • 缺点

    • 必须使用命名路由的方式传参
    • 刷新会丢失

query传参的优缺点

  • 优点

    • 刷新不会丢失
    • 可以使用命名路由的方式传参也可以用路径跳转传参
  • 缺点

    • 显示在地址栏上,信息暴露
    • 如果传递参数过长,部分浏览器限制url输入长度,导致数据缺失,过长的url也影响美观

知道了params和query区别和优缺点,我们就知道为什么可能要用params的方式传参了,因为有时候业务需要url不能过长,数据不想要直接展示在url上

2.怎么实现Params 传参实现刷新也会保留数据

可以配合localStorage使用
  1. A跳转路由到B,通过params传值,并把params的值存到localStorage中

  2. B页面中,通过this.$route.params 获取参数 params

    1. 如果params中存在数据说明页面没刷新,直接使用
    2. 如果params不存在,获取本地缓存的参数数据
  3. 实现功能

// 创建一个js文件 使用全局mixins,方便方法的使用,route-mixins.js
const identifying = '$RT' // 特殊标识,做区分使用
/**
 * 判断是否是 "" 或 undefined 或 null 或 {} 或 []
 * @param data
 * @returns {Boolean}
 */
function isBlank (t) {
    return t === "" || t === undefined || isNull(t) || (isObject(t) && JSON.stringify(t) === "{}") || (isArray(t) && t.length < 1);
}
​
export default {
  data () {
    return {}
  },
​
  methods: {
    /**
      * 跳转路由,并存下 params
      * @param {String|Object} route 路由对象
      * @param {Boolean} isStorage 是否使用storage
      * @param {Boolean} isPush 是否使用 push 跳转
      */
    $openPageParams (route, isStorage = true, isPush = true) {
        // 判断是否为对象
        if (route instanceof Object) {
            // 解构出params
            const { name, params } = route
            // 判断是否需要存localStorage 并且 不为空对象
            if (isStorage && !isBlank(params)) {
                // 将数据转码放入localStorage中,如果会加密,把数据加密更安全哦   
                const data = encodeURIComponent(JSON.stringify(params))
                localStorage.setItem(`${identifying}${name}`, data)
            }
        }
        if (isPush) {
            // 跳转路由   push     
            this.$router.push(route)
        } else {
            this.$router.replace(route)
        }
      
    },
​
    // B页面获取参数使用方法
    $getRouteParams () {
        // 将数据解构
        let { params, name, ...route } = this.$route
        // 如果 params 不存在数据
        if (isBlank(params)) {
            // 获取本地数据
            const localParams = localStorage.getItem(`${identifying}${name}`)
            // 本地数据不为空
            if (!isBlank(localParams)) {
                params = JSON.parse(decodeURIComponent(localParams))
            }
        }
        // return 路由对象
        return { ...route, name, params: params || {} }
    },
​
    // 关闭路由,并跳转到下一个路由(建议关闭路由用这个,因为这个可以把localStorage清除)
    $closePageParams (closeRoute, nextRoute, isStorage = true) {
      // 先获取参数
      const { name } = this.$getRouteParams()
      localStorage.removeItem(`${identifying}${name}`)
      this.$nextTick(() => {
        // 判断是否需要跳转到下一个路由
        if (!isBlank(nextRoute)) {
            // 跳转下一个路由
            this.$openPageParams(nextRoute, isStorage, false)
        } else {
          this.$router.go(-1)  
        }
      })
    }
  }
}