wepy 和 redux 结合的连接器
安装
npm install wepy-redux --save
示例
<template> <view class="container"> <text class="info">{{num}}</text> <text class="info">{{inc}}</text> <button @tap="addNum" size="mini"> + num </button> <button @tap="asyncInc" size="mini"> async inc </button> </view></template> <script> import wepy from 'wepy' import { connect } from 'wepy-redux' import List from '../components/list' import Panel from '../components/panel' import Counter from '../components/counter' import Group from '../components/group' import Toast from 'wepy-com-toast' import { INCREMENT } from '../store/types/counter' import { asyncInc } from '../store/actions' import testMixin from '../mixins/test' @connect({ num(state) { return state.counter.num }, inc: 'inc' }, { addNum: INCREMENT, asyncInc }) export default class Index extends wepy.page { // ... methods = { // ... } // ... onLoad() { } }</script>
使用
- 初始化 store
// app.wpy const store = // set!!
- 得到 store
const store = // 可以直接使用 store 实例了// dispatchstore// stateconst state = store
- 连接组件,就以上边的示例来说明
// ... @ page // ... methods = // ... // ... { }
这里主要涉及到 connect
的用法: connect(states, actions)
,这里解释下:
-
states
: 访问 state 上的值,可以是数组或者对象,如果是对象的话,则包含的是K-V
对,V
可以是函数还可以是字符串,如果是字符串的话则默认获取state[V]
, 否则的话则是使用返回值;而对于如果是数组的话(数组中的项只能为字符串),则认为是相同的K-V
对象结构。states
最终会附加到组件的computed
属性值上。 -
actions
: 只能传入对象,对象的K-V
结构,如果V
是字符串的话,则直接会distatch
如下的结构:// args 就是调用传入参数type: val// 修正一般情况下的参数 一般支持只传一个参数// 如果真的是多个参数的话 那么 payload 就是参数组成的数组payload: argslength > 1 ? args : args0如果是一个函数 fn,则会
dispatch(val.apply(store, args))
,否则的话则直接dispatch(V)