0

0

0

修罗

站点介绍

只有了解事实才能获得真正的自由

微信小程序开发(三)状态管理

修罗 2022-04-01 1279 0条评论 微信小程序

首页 / 正文

微信小程序状态管理

方案一:

将全局状态放在app.js文件的globalData中;

使用getApp().globalData获取数据;

缺点:数据不是响应式

https://developers.weixin.qq.com/miniprogram/dev/reference/api/getApp.html

1660148780515.png

方案二:

使用第三方库hy-event-store:

https://github.com/coderwhy/hy-event-store

npm i hy-event-store

使用库

1660150405955.png

store_a.js

import { HYEventStore } from 'hy-event-store'

const aStore = new HYEventStore({
  state: {
    a: {name:'coder'}, 
  },
  actions: {
    async getRankingDataAction(ctx) {
     console.log(11)
     let pro = await new Promise((res, rej) => {
        setTimeout(() => {
          res("haha")
          ctx.a = {name: 'xiuluo'}
        },3000)
      })
      console.log(pro)
      console.log('haha2')
    }
  }
})

export {
  aStore
}

index.js

export * from './store_a'
页面引入index.js
import { aStore } from "../../store/index.js";
...

// 发起共享数据的请求
aStore.dispatch('getRankingDataAction')
// 从store获取共享的数据
aStore.onState("a", (res) => {
    console.log(res.name)
})

1660150656569.png

评论(0)


最新评论

  • 1

    1

  • 1

    1

  • -1' OR 2+158-158-1=0+0+0+1 or 'TKCTZnRa'='

    1

  • 1

    1

  • 1

    1

  • 1

    1

  • 1

    1

  • @@5Qa2D

    1

  • 1

    1

  • 1

    1

日历

2025年09月

 123456
78910111213
14151617181920
21222324252627
282930    

文章目录

推荐关键字: Linux webpack js 算法 MongoDB laravel JAVA jquery javase redis