Vuex 笔记

官方学习链接:https://vuex.vuejs.org/zh/

 

项目结构:

https://vuex.vuejs.org/zh/guide/structure.html

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 购物车模块
        └── products.js   # 产品模块

思路:

1.mutation改变state的状态

2.action commit mutaion

3. store.dispatch.action

 

代码:

代码学习例子:

https://github.com/vuejs/vuex/blob/dev/examples/counter/store.js

 

main.js

全局引入vuex

import store from './store/index'

new Vue({
  store,
  render: h => h(App)
}).$mount('#app');

index.vue

使用vuex:



index.js

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import common from './modules/common'
import location from './modules/location'

Vue.use(Vuex);

const store = new Vuex.Store({
    modules: {
        common,
        location,
    },
    state,
    mutations,
    actions
});
export default store

 

state.js

export default {
	count: 1
}

 mutations.js

export default {
	increment(state) {
		state.count++
	}
}

actions.js

export default {
	increment({commit}) {
		commit('increment')
	}
}

 

你可能感兴趣的:(vue)