码迷,mamicode.com
首页 > Web开发 > 详细

vue url解析函数

时间:2017-04-30 12:35:57      阅读:240      评论:0      收藏:0      [点我收藏+]

标签: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解析函数

标签:log   class   exp   created   地址   out   substring   url   ack   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!