vue状态管理vue-vux使用

来源:互联网 发布:淘宝买鲜花会折么 编辑:程序博客网 时间:2024/06/05 08:02

相关好文

  • Vue2.0 框架配置:vue-cli + vue-router + vuex
  • Vuex 2.0 源码分析

一.state — 数据

简单使用1. Vue.use(Vuex)2. 注入, new vue({el:...store,...})3. 然后在所有组件中可以通过$store.state.xxx获取,动态数据,通过computed可以实时更新

二.getters — 获取数据 (局部或默认状态,其他getter,根状态)

对state中的数据过滤或者计算

getters:{    todoDone:state=>{        return state.todos.filter(todo=>todo.done)    },    将todos遍历,每条为todo传入匿名函数,返回todo.done为真的那条    todoDoneLength:(state,gettrers){        renturn getters.todoDone.length    }    接受getters作为第二参数,使用getters后的数据}

三.Mutations — 数据更新 (局部或默认状态,载荷)

const store = new Vuex.Store({  state: {    count: 1  },  mutations: {    increment (state,payload) {      // 变更状态 不能使用异步函数的回调      state.count=state.count+payload.data    }  }})

然后

store.commit("increment",{    data:10})

或者

store.commit({type:"increment",payload:{}})

触发事件,更改数据,payload载荷,设置为对象更易读

四.actions — 可以异步执行mutations

(类store,通过参数解构{state,rootState,commit},内部直接使用,不用带context)
(一般在组件中就只调用actions)

在actions内放置异步函数,然后触发mutation内的事件actions:{    increment (context){        context.commit("increment")    }或者    increment ({commit}){        commit("increment")    }}context是一个与store实例相同的对象{commit}是通过参数结构将context中的commit方法当做参数传入通过store.dispatch("increment")通过promise等组合actions,即一个actions调用完后调用下一个actions事件

五. modules — 模块化状态树

类似于vue的模块使用方法

const module_a={    state:{},    mutations:{}...}var store = new Vuex.Store({    modules:{        a:module_a,        b:module_b    }})然后通过store.state.a.count 访问数据

mutation 和 getter : 第一个参数是模块的局部状态

  • action : context.state 是局部状态,根节点的状态是 context.rootState
  • getter : 根状态会作为第三个参数
  • 命名空间—因为mutations等都是全局的,所以通过将变量名设为来设置命名空间

如:

const TDONE = "TODO/DONE"然后 type form xxx.js[type.TDONE] (state) {...}

其他

一.表单处理

v-model绑定如果是引用类,就会在修改value时,直接修改state

解决:

通过set,get方法

computed: {  message: {    get () {      return this.$store.state.obj.message    },    set (value) {      this.$store.commit('updateMessage', value)    }  }}
原创粉丝点击