1:vuex中,有默认的五种基本的对象:
state:存储状态(变量)。getters:state的计算属性。 $sotre.getters.fun()。mutations:修改状态,同步的,类似自定义事件。$store.commit('',params)。actions:异步操作。$store.dispath('')。modules:store的子模块,为了开发大型项目,方便状态管理而使用的。2:小小实列-->数据读取:
安装:npm install vuex --save
store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { count: 0 } export default new Vuex.Store({ state })main.js
import Vue from 'vue' import App from './App' import router from './router' import store from './vuex/store' // 引入store Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })hello.vue
<template> <div class="hello"> <h3>{{$store.state.count}}</h3> </div> </template>3:小小实列-->数据修改同步mutations和异步actions
main.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //存放数据 const state = { count: 0 } //获取state,相对于state的一个计算属性 const getters = { getterCount(state, n = 0) { return (state.count += n) } } //同步对数据修改 const mutations = { mutationsAddCount(state, n = 0) { return (state.count += n) }, mutationsReduceCount(state, n = 0) { return (state.count -= n) } } //异步对数据修改 const actions = { actionsAddCount(context, n = 0) { console.log(context) return context.commit('mutationsAddCount', n) }, actionsReduceCount({ commit }, n = 0) { return commit('mutationsReduceCount', n) } } export default new Vuex.Store({ state, getters , mutations, actions }) hello.vue <template> <div class="hello"> <h3>{{$store.state.count}}</h3> <div> <button @click="handleAddClick(10)">增加</button> <button @click="handleReduceClick(10)">减少</button> </div> </div> </template> hello.vue methods: { //mutations同步 handleAddClick(n){ this.$store.commit('mutationsAddCount',n); }, handleReduceClick(n){ this.$store.commit('mutationsReduceCount',n); } //actions异步 handleActionsAdd(n){ this.$store.dispatch('actionsAddCount',n) }, handleActionsReduce(n){ this.$store.dispatch('actionsReduceCount',n) } }├── index.html ├── main.js ├── api │ └── ... # 抽取出API请求 ├── components │ ├── App.vue │ └── ... └── store ├── index.js # 我们组装模块并导出 store 的地方 ├── actions.js # 根级别的 action ├── mutations.js # 根级别的 mutation └── modules ├── cart.js # 购物车模块 └── products.js # 产品模块