Skip to content

theajack/mp-mixin

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
npm
 
 
 
 
src
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

mp-mixin

stars forks version downloads issue

author license Size TopLang Dependent test

🚀 微信小程序 mixin 和 store 方案

English | 使用demo | 更新日志 | 反馈错误/缺漏 | Gitee


1. 特性

  1. 支持 mixin data、methods、生命周期及Page事件
  2. 支持不同 Page 和 Component之间 使用 store 共用状态
  3. 支持全局 mixin 和 store
  4. typescript编写
  5. 支持QQ小程序 以及其他api和微信小程序相似的小程序
  6. 体积小巧,仅 1.83kb

2. 快速使用

2.1 npm 安装

npm i mp-mixin
import 'mp-mixin';

2.2 cdn

点击下载 cdn 文件,复制到您的小程序项目中,然后 import 这个文件就可以

cdn地址: https://cdn.jsdelivr.net/npm/mp-mixin/mp-mixin.min.js

2.3 快速使用

2.3.1 mixin 对象

mixin 是一个对象,数据结构如下

const store = wx.creteStore({});

const mixin = {
    data: {}, // 可选
    methods: {}, // 可选
    store: store, // 可选 当全局注入时,store可以是一个json, 否则 必须是 store对象
    // 以下为Page独有的生命周期或事件
    // 详情请参考小程序文档 
    onLoad(){

    },
    onShareAppMessage(){

    },

    // 以下为Component独有的生命周期或事件
    lifetimes:{
        // 详情请参考小程序文档 
    },
    pageLifetimes:{
        // 详情请参考小程序文档
    }
}

微信小程序Page文档

微信小程序Component文档

2.3.2 全局mixin

全局mixin, 推荐在 app.js 中引入

import 'mp-mixin';
wx.mixin(mixin); // mixin 对象 见 2.3.1

2.3.3 Page mixin

也可以在Page构造中按需引入 mixin

Page({
    mixin: mixin, // mixin 对象 见 2.3.1
    // ...
})

2.3.4 Component mixin

也可以在Component构造中按需引入 mixin

Component({
    mixin: mixin, // mixin 对象 见 2.3.1
    // ...
})

说明

  • 如有相同的键值对,优先级为 组件 > 局部mixin > 全局mixin
  • data 优先级 高于 store
  • mixin 中的 data 会被深克隆分别注入对应的Page中的data,使用setData互不影响
  • mixin 中的 store也会被注入Page中的data,区别是如果不同Page引入的是同一个,则一个页面setData会影响其他页面的 状态,且UI会更新

3 api

引入 mp-mixin 之后,mp-mixin 会将一下三个 api 挂载到 wx 对象上

wx.mixin
wx.createStore
wx.initGlobalStore

wx.initGlobalStore 等价于在 wx.mixin 方法中加入 store属性

wx.initGlobalStore({
    // state
})

wx.mixin({
    store: {
        // state
    }
})

您也可以主动引入来使用上述三个API

import {globalMixin, createStore, initGlobalStore} from 'mp-mixin'
// ...

您可以通过 injectStaff 方法手动注入到任何对象上

import {injectStaff} from 'mp-mixin'
injectStaff(anyObject);

获取 mp-mixin version

wx.mpMixinVersion

// 或者

import {version} from 'mp-mixin';

4. 类型声明

  1. type.d.ts
  2. index.d.ts

About

微信小程序 mixin & 全局store 方案

Resources

License

Stars

Watchers

Forks

Packages

No packages published