小程序 - 状态管理

手动构造

小程序官当暂时没有提供状态管理模式,可以使用globalData实现一个简单的状态管理

// app.js
App({
  globalData: {
    count: 1 // 定义全局变量
  },

  // 初始化函数。进入页面 onShow() 阶段调用,在页面 data 中使用全局变量
  initData(_this, params) {
    let obj = {}
    params.forEach((key) => {
      obj[key] = this.globalData[key]
    })
    _this.setData(obj)
  },

  // 更新全局变量的值,同时更新页面 data 中的值
  addCount(_this) {
    this.globalData.count += 1
    // 执行完后更新
    this.initData(_this, ['count'])
  }
})

在需要使用到全局变量页面的 onShow() 阶段,调用 app.initData() 将全局变量绑定到该页面视图层中

// home.js
const app = getApp()

Page({
  data: {},
  
  onShow: function () {
    app.initData(this, ['count'])
  },
  
  addCount() {
    app.addCount(this)
  }
})

Westore

Westore - 微信小程序解决方案

1.下载并引入 create.js、diff.js

2.新建 state/store.js,在 data 中声明全局变量

export default {
  data: {
    userInfo: {}
  }
}

3.在 page 页面的 js 文件中引入 create.js、store.js,并对 Page() 构造函数稍做修改

Page({
  ...
})

改为:

import store from '../../state/store.js'
import create from '../../utils/create.js'

create(store, {
  data: {
    userInfo: {}, // 此页面使用到全局变量,需要先声明
    place: ''
  },
  loadUser() {
    this.store.data.userInfo = {name: 'Kobe'} // 修改全局变量 userInfo
    this.store.data.place = 'LA'              // 修改当前页面 data 中的 place
    this.update()
  }
})

4.如果是 Component 组件,则不需要引入 store.js

import create from '../../utils/create.js'

create({
  ready: function () {
   //you can use this.store here
  },

  methods: {
    //you can use this.store here
  }
})
发布了93 篇原创文章 · 获赞 20 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/sinat_33184880/article/details/103494494