vuejs解析url地址

函数:

// 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更简单

原文地址:https://www.cnblogs.com/yesyes/p/6788869.html