標籤:log class exp created 地址 out substring url ack
函數:
// url解析函數// ?id=111&name=567 => {id:111,name:567}export function urlParse(){ let obj = {}; let reg = /[?&][^?&]+=[^?&%]+/g; let url = window.location.search; let arr = url.match(reg); arr.forEach((item) => { let tempArr = item.substring(1).split(‘=‘); let key = decodeURIComponent(tempArr[0]); let val = decodeURIComponent(tempArr[1]); obj[key] = val; }) return obj;}
函數作用:解析url地址獲得一個對象
使用方法:把以上代碼添加到你的公用函數庫
<tempalte></tempalte><script>import {urlParse} from ‘urlParse.js‘; export default { data() { return { news: { id: (() =>{ let get = urlParse(); // console.log(get.id); 123 return get.id; })() } } } // 發送帶參數的請求 created() { this.$axios.get(‘/api/news?id=‘ + this.news.id).then((res) => { // success callback let myData = res.data.data; // 合并對象 this.news = Object.assign({},this.news,myData); }) } }</script>
其實用vue-router更簡單
vue url解析函數