vuex基础

什么是 Vuex?

Vuex 是 Vue .js 应用程序的状态管理模式 + 库。它充当应用程序中所有组件的集中式存储,其规则确保状态只能以可预测的方式进行更改。

如果您从未构建过大型SPA并直接跳入Vuex,它可能会感到冗长和令人生畏。这是完全正常的 - 如果你的应用程序很简单,那么建议不需要使用Vuex!

安装

npm install vuex@next --save
yarn add vuex@next --save

开始

1.整个store文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

2 state 状态?

//作为vuex储存数据的地方
state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
2.1 组件引用state
$store.state.todos

3 getters 您可以将它们视为存储的计算属性

//装饰 类似于计算属性
getters: {
  // ...
  doneTodosCount (state, getters) {
    return getters.doneTodos.length
  }
}
3.1调用getters
store.getters.doneTodosCount

4 mutations 突变

//处理程序函数是我们执行实际状态修改的地方,它将接收状态作为第一个参数:
mutations: {
    increment (state) {
      // mutate state
      state.count++
    }
  }
3.1mutations 传参
mutations: {
  increment (state, n) {
    state.count += n
  }
}
3.2调用mutations
store.commit('increment',5)

4.actions 行动

操作不会改变状态,而是提交突变。
操作可以包含任意异步操作。

//在实践中,我们经常使用ES2015参数解构来简化代码(特别是当我们需要多次调用时):commit
actions: {
  increment ({ commit }) {
    commit('increment')
  }
}
  actions: {
  //不解构的时候context 指向mutations
    increment (context) {
      context.commit('increment')
    }
  }
4.1调用actions
this.$store.dispatch('xxx') 
mapActions
store.dispatch
store
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值