js獲取url參數值的幾種方式

1、原生js獲取URL參數值:正則表達式

  好比當前URL爲:http://localhost:8080/#/page2?id=100&name=guanxy函數

<template>
  <div>
    <div>
      <button style="background-color: orange" @click="getUrlParam">方式一:採用正則表達式獲取地址欄參數 (代碼簡潔,重點正則)</button>
      <p>結果:id={{method1_id}},name={{method1_name}}</p>
    </div>
    <div>
      <button style="background-color: green" @click="getUrlParam2"> 方法二:split拆分法 (代碼較複雜,較易理解)</button>
      <p>結果:id={{method2_id}},name={{method2_name}}</p>
    </div>
    <div>
      <button style="background-color: aqua" @click="getUrlParam3"> 方法三:split拆分法(根據參數名獲取對應的值)</button>
      <p>結果:id={{method3_id}},name={{method3_name}}</p>
    </div>
  </div>
</template>

<script>
  export default {
    name: "page2",
    data() {
      return {
        method1_id: '',
        method1_name: '',
        method2_id: '',
        method2_name: '',
        method3_id: '',
        method3_name: '',
      }
    },
    methods: {
      getUrlParam() {
        //爲何window.location.search取值爲空?
        //「http://localhost:8080/#/page2?id=100&name=guanxy」那麼使用window.location.search獲得的就是空(「」)。
        // 由於「?id=100&name=guanxy」串字符是屬於「#/page2?id=100&name=guanxy」這個串字符的,也就是說查詢字符串search只能在取到「?」後面和「#」以前的內容,若是「#」以前沒有「?」search取值爲空。
        this.method1_id = this.getQueryString('id');
        this.method1_name = this.getQueryString('name');
      },
      getQueryString(name) {
        let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        let url = window.location.hash.split('?')[1].match(reg);
        // console.log(url)
        if (url != null) {
          return decodeURI(url[2])//decodeURI() 函數可對 encodeURI() 函數編碼過的 URI 進行解碼。
        } else {
          return null
        }
      },
      getUrlParam2() {
        let url = window.location.hash.split('?')[1].split("&");
        // console.log(url)
        let paramObj = new Object()
        url.forEach((item, i) => {
          paramObj[item.split('=')[0]] = item.split('=')[1]
        })
        this.method2_id = paramObj.id,
          this.method2_name = paramObj.name
      },
      getUrlParam3() {
        this.method3_id = this.getQueryVariable('id');
        this.method3_name = this.getQueryVariable('name')
      },
      getQueryVariable(variable) {
        let url = window.location.hash.split('?')[1].split("&");
        for (let i = 0; i < url.length; i++) {
          let pair = url[i].split('=');
          if (pair[0] == variable) {
            return pair[1]
          }
        }
        return false
      }
    }
  }
</script>

<style scoped>

</style>

頁面效果:this

2、Vue 獲取URL參數值編碼

  <p>params獲取當前路由參數:id={{this.$route.params.id}},name={{this.$route.params.name}}</p>
  <p>query獲取當前路由參數:id={{this.$route.query.id}},name={{this.$route.query.name}}</p>
相關文章
相關標籤/搜索