ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

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

2026/9/15 20:10:39 拓冰建站 浏览量
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; //Aitems.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);}},...
}