函數:vue
// 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地址得到一個對象ios
使用方法:把以上代碼添加到你的公共函數庫vue-router
<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更簡單axios