以商家收藏
这一功能为例:
2、seller.vue: 设置和读取localstorage
----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); } }}{ {favoriteText}}
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;}
原文链接:http://blog.csdn.net/u013217071/article/details/73379128