本文主要是介绍vue+localStorage+收藏+解析url参数 实例解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以商家收藏
这一功能为例:
1. 首先App.vue中根据url 设置好 商家的id
<script>
import {urlParse} from './common/js/util.js'
import Header from './components/header/Header.vue'const err_OK = 0;export default{data(){return { /* 商家默认有id */seller:{id:(()=>{/* 从地址栏中的url中通过urlParam函数解析,得到id */let queryParam = urlParse();console.log(queryParam);return queryParam.id;})()}}},created(){this.$http.get('./api/seller?id='+this.seller.id).then((res)=>{var resData = res.data;if(resData.errno === err_OK){/* this.seller = resData.data; 会覆盖掉id *//* 防止把id覆盖掉,使用es6的一个语法:扩展了对象的属性,在原来的基础上添加response.data的值,不会覆盖掉原来的id属性 */this.seller = Object.assign({},this.seller,resData.data);console.log(this.seller.id);}},(res)=>{alert(res.status);});},components: {'v-header': Header}
}
</script>
2、seller.vue: 设置和读取localstorage
<div class="favorite" @click="toggleFavorite($event)"><span class="icon icon-favorite" :class="{'active':favorite}"></span><div class="text">{{favoriteText}}</div>
</div>----
import {saveToLocal,loadFromLocal} from '../../common/js/store.js'
export default{props:{seller: {type: Object}},data(){return{favorite: (()=>{return loadFromLocal(this.seller.id,'favorite',false);})()}},computed:{favoriteText(){return this.favorite? '已收藏': '收藏';}},methods:{toggleFavorite(event){if(!event._constructed){return;}this.favorite = !this.favorite;saveToLocal(this.seller.id, 'favorite', this.favorite);}}
}
3、保存的读取localStorage的接口—-store.js:
/*** [保存数据到localstorage]* @param {[Number]} id [商家id]* @param {[type]} key [属性值]* @param {[type]} value [value值]* @return {[type]} [description]*/
export function saveToLocal(id, key, value) {let seller = window.localStorage.__seller__;if (!seller) {seller = {};seller[id] = {};} else {seller = JSON.parse(seller);if (!seller[id]) {seller[id] = {};}}seller[id][key] = value;window.localStorage.__seller__ = JSON.stringify(seller);
};
/*** [从localstorage读取数据]* @param {[Number]} id [商家id]* @param {[type]} key [属性值]* @param {[type]} def [属性值的默认取值,当没有保存key时,返回默认值]* @return {[type]} [属性值对应的value值]*/
export function loadFromLocal(id, key, def) {let seller = window.localStorage.__seller__;if(!seller){return def;}seller = JSON.parse(seller);if(!seller[id]){return def;}let ret = seller[id][key];return ret || def;
}
4.util.js:
/*** [解析url参数]* @example ?id=12345&a=1* @return Object {id:12345,a:1}*/
export function urlParse(){let url = decodeURIComponent(window.location.search);let obj = {};let reg = /[?&][^?&]+=[^?&]+/g;//['?id=12345','a=1']let arr = url.match(reg);if(arr){arr.forEach((item)=>{let tempArr = item.substring(1).split('=');let key = decodeURIComponent(tempArr[0]);let value = decodeURIComponent(tempArr[1]);obj[key] = value;})}return obj;
}
这篇关于vue+localStorage+收藏+解析url参数 实例解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!