UNIAPP中借助store+watch完成实时数据

简介

  • 手机端蓝牙连接校验仪,校验仪上传校验数据至手机完成展示。
  • 基于watch,完成实时展示数据。
  • 对象放在store中。
  • 实现分为store中的配置,数据接收,数据展示

store配置

  • 在state中配置属性,在mutations中配置更新方法,在getters中配置属性获取方法。
const store = createStore({
	state: {
		itemStatus: {}
	},
	mutations: {
		//更新数据
		updateItemStatus(state, newValue) {
			state.itemStatus= newValue;
		}
	},
	getters: {
		getItemStatus(state) {
			return state.itemStatus;
		}
	},
	actions: {}
})

数据接收

const mockDataUpdate = function(items) {
	const itemStatus= store.getters.getItemStatus; //A
	items.forEach(item => {
		if (indexStatus[item] === undefined) {
			indexStatus[item] = 2;
		} else if (indexStatus[item] === 2) {
			indexStatus[item] = [0, 1][Math.round(Math.random())];
		}
	});
	let newItemStatus = {};
	Object.assign(newItemStatus , itemStatus);
	store.commit("updateItemStatus", newItemStatus );//B
}

/**
 * @param {Object} items 数据项
 * 模拟数据上报
 */
const startCalibrate = function (items) {
	mockDataUpdate(items);
	let index = 0;
	let intervalIndex = setInterval(() => {
		index++;
		mockDataUpdate(items);
		if (index > 10) {
			clearInterval(intervalIndex);
		}
	}, 5000);
}
备注
  • A: 这里注意,store中申明的是方法,这里按照对象调用。
  • B: 这里发现,只要新对象就会触发watch,如果是旧对象反复赋值不会触发watch。

数据展示

  • 使用watch实现数据的实时展示。
export default {
	...
	computed: {
		itemStatus() {
			return this.$store.state.itemStatus;
		}
	},
	watch:{
		itemStatus(newVal, oldVal) {
			console.log("watch itemStatusfunc");
			console.log(newVal);
		}
	},
	...
}

第二种

  1. 如果数据简单的话,并不需要使用store和watch。
  • 模拟变更处代码如下:
const createPro1 = function() {
	return {
		key: Math.random()
	}
}


const allData = {
	childData: {
		pro1: createPro(),
		pro2: createPro()
	}
}

const startChange = function() {
	let index = 0;
	const intervalIndex = setInterval(() => {
		index++;
		if (index > 5) {
			clearInterval(intervalIndex);
			return; 
		}
		const pro1 = createPro();
		Object.assign(allData.childData.pro1, pro1);//B
	}, 2000)
}

export {
	allData,
	startChange,
}
  • 数据展示处代码如下:
<uni-tr>
	<uni-td align="center" style="width: 50%">仿真数据</uni-td>
	<uni-td align="center">{{mock.key}}</uni-td>
</uni-tr>
import {allData, startChange} from "@/common/connectDevice.js";
export {
	onLoad() {
		startChange();
	},
	data() {
		return {
			mock: allData.childData.pro1,//A
			...
		}
	},
	...
}
  • 备注
  1. 注意代码中A和B处层级是一致的。比如除上文所写外,还可以写成:
//B
allData.childData = {
	pro1: createPro(),
	pro2: createPro()
}

//A
mock: allData
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田秋浩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值