美文网首页程序员微信小程序微信小程序开发
微信小程序全局状态管理和跨页通讯-使用Westore就够了

微信小程序全局状态管理和跨页通讯-使用Westore就够了

作者: 独孤久见 | 来源:发表于2018-09-27 11:28 被阅读56次

现在市面上有很多小程序的框架,看上去都挺高大上,但是实际用起来却没能真正解决项目的痛点,一般的都是为了写法的方便都差不多运用vue的写法进行改造,但是小程序本身具有组件化、开发、调试、发布、灰度、回滚、上报、统计、监控和最近的云能力都很强悍,有时真没必要还要去查看其它框架两份文档进行开发。
通过一段时间的小程序开发,发现小程序现在的痛点其实真正是全局状态管理和跨页面通信,就像vuex进行状态管理,虽然也有类似Redux状态管理库,但是使用起来比较麻烦。 有时候要定义一个全局的数据往往会弄缓存,但是这是下下策。
最近看到大神写Westore框架或者说成是库吧,嘛嘛再也不用担心我编程了。下面就入门级的介绍一下这个框架的使用。

一、页面结构

页面结构

项目结构和原生的目录没有区别,只不过主要多加了在utils里面的diff.js、create.js以及store.js。里面的diff是核心的库文件,create主要是页面注册用的,而store就是管理全局的数据中心。是不是一目了然。

二、页面注册及组件注册

创建页面

创建 Page 只需传入两个参数,store 从根节点注入,所有子组件都能通过 this.store 访问。原生的方法还是一样使用,不影响。 this.update()类似this.setData()但是 this.update 调用的 setData 是 diff 后的,所以传递的数据更少。

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

const app = getApp()

create(store, {

  onLoad: function () {
    if (app.globalData.userInfo) {
      this.store.data.userInfo = app.globalData.userInfo
      this.store.data.hasUserInfo = true
      this.update()
    } else if (this.data.canIUse) {
      app.userInfoReadyCallback = res => {
        this.store.data.userInfo = res.userInfo
        this.store.data.hasUserInfo = true
        this.update()
      }
    } else {
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.store.data.userInfo = res.userInfo
          this.store.data.hasUserInfo = true
          this.update()
        }
      })
    }
  }

})

绑定数据

和以前的写法没有差别,直接把 store.data 作为绑定数据源。

创建组件

和创建 Page 不一样的是,创建组件只需传入一个参数,不需要传入 store,因为已经从根节点注入了。

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

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

  methods: {
    //you can use this.store here
  }
})

跨页面同步数据

使用 westore 你不用关心跨页数据同步,你只需要专注 this.store.data 便可,修改完在任意地方调用 update 便可

感觉使用是不是很简单并且this.update 比原生 setData 的性能更优,更加智能。

westore库作者GitHub地址:https://github.com/dntzhang/westore

相关文章

网友评论

    本文标题:微信小程序全局状态管理和跨页通讯-使用Westore就够了

    本文链接:https://www.haomeiwen.com/subject/ttwsoftx.html