vue动态获取地址栏参数

  data () {
    return {
      seller: {
        // 从url获取id参数
        id: (() => {
          let obj = {};
          // 获取url参数部分 大概长这样 ?id=213123&a=b
          let url = window.location.search;
          let reg = /[?&][^?&]+=[^?&]+/g;
          // 用正则匹配成数组 大概长这样 [?id=213123, &a=b]
          let arr = url.match(reg);
          if (arr) {
            arr.forEach((item) => {
              // 把字符串?id=123 转为数组 [id, 123]
              let tempArr = item.substring(1).split('=');
              // decodeURIComponent()可对encodeURIComponent()函数编码的URI进行解码。
              let key = decodeURIComponent(tempArr[0]);
              let val = decodeURIComponent(tempArr[1]);
              // 把键值对添加到obj中
              obj[key] = val;
            })
          }
          console.log(obj.id);
          return obj.id;
        })()
      }
    }
  },

请求数据时候就可以用地址栏的参数了

  created () {
    this.$ajax.get('/api/seller?id=' + this.seller.id).then((res) => {
      // 用Object.assign()方法赋值 不会覆盖seller已经存在的属性
      this.seller = Object.assign({}, this.seller, res.data.data);
    })
  }

猜你喜欢

转载自www.cnblogs.com/gr07/p/9105415.html