Vue前端

WePY中Redux学习

2019-04-12  本文已影响13人  打酱油12138

WePY是Vue封装的让小程序支持组件化开发的框架

WePY官方文档

重点学习Redux

Redux是状态管理的框架(更简单的实现全局通信和状态管理)

这里参考了阮一峰大神的教程
Redux入门教程

Redux设计思想:

主要分为三部分:

名称 属性 理解
action 动作 可执行的方法
reducers 发起动作返回状态 state下的状态值(K-V)
types 方法名

使用的是WePY框架下的wepy-redux:

// 构建全局状态
const store = configStore()
setStore(store)

// 发出动作,更新状态 
// xx: 动作名  y:传入参数
store.dispatch( xx( y ) )

// 获取state下x的z属性
store.getState().x.z

wepy-redux简单使用

computed: {
    count () {
      return store.state.count
    }
}
const app = new Vue({
  el: '#app',
  // 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,
  components: { Counter },
  template: `
    <div class="app">
      <counter></counter>
    </div>
  `
})
computed: {
    count () {
      return this.$store.state.count
    }
  }
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

getter(store的计算属性)

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

记录下目前对redux的理解和使用,对后续深入学习redux和vuex应该会有所帮助。
后面会更新对redux的理解

未完待续

上一篇 下一篇

猜你喜欢

热点阅读