uniapp缓存对象数组

需求:使用uniapp,模拟key(表名)增删改查对象数组,每个key可以单独操作,并模拟面对对象对应表,每个key对应的baseInstance 类似一个操作类,当然如果你场景比较简单,可以改为固定key或者传值key,调普通js而不需要new

base.js

export default {

	data() {
		return {}
	},


	methods: {

		// 一是不需要new来调用,二是参数非常灵活,可以不传,也可以这么传
		createBaseStore(key) {
			return new this.baseInstance(key || {})
		},
		// 函数创建对象 每个key对应自己的方法 达到实例化效果 使用 baseInstance.addExt(obj) 自动携带固定key
		baseInstance(key) {
			this.dataKey = key;

			this.addExt = function addExt(obj) {
				var dataList = this.getAllExt()
				if (dataList == null) {
					dataList = new Array()
				}
				var newItemid = 0
				const last = dataList.length - 1
				if (last >= 0) {
					newItemid = dataList[last].id + 1
				}
				obj.id = newItemid
				dataList.push(obj)
				this.save(dataList)
			}



			this.removeExt = function removeExt(param) {

				var dataList = this.getAllExt();
				var findItemIndex = dataList.findIndex(item => {
					if (item.id == param) {
						return true
					}
				})

				if (findItemIndex >= 0) {
					const newList = dataList.splice(findItemIndex, 1)
					console.log("remove item is index", findItemIndex, JSON.stringify(newList))
					this.save(dataList)
				} else {
					console.log("not find remove param", param)
				}

			}

			this.changeExt = function changeExt() {
				console.log("change")
			}

			this.searchExt = function searchExt() {
				console.log("search")
			}

			this.save = function save(dataList) {
				var dataJson = JSON.stringify(dataList)
				uni.setStorage({
					key: key,
					data: dataJson,
					success: function() {
						console.log("key:", key, 'addExt success', dataJson);
						console.log('curr size', dataList.length);
					}
				});

			}


			this.getAllExt = function getAllExt() {
				try {
					const value = uni.getStorageSync(this.dataKey);
					if (!value) {
						console.log('getAllExt is empty');
						return null
					}

					const dataBean = JSON.parse(value)
					if (dataBean) {
						return dataBean
					}
				} catch (e) {
					console.log("showAllToLogExt error", e);
				}

				return null
			}


			this.showAllToLogExt = function showAllToLogExt() {
				try {
					const value = this.getAllExt();
					if (value) {
						console.log("showAllToLogExt", value);
					}
				} catch (e) {
					console.log("showAllToLogExt error", e);
				}

			}

		},

		clearAllExt() {
			console.log("clearAllExt")
			uni.clearStorage()
		}

	}

}

vue使用





你可能感兴趣的:(uni-app,缓存,javascript)