此文主要为了举例说明vue2.0配合使用vuex,具体文档可以参考vuex官网
1、初始化
mkdir vue-vuex-demo
cd vue-vuex-demo
vue init webpack-simple vuex-test-demo
npm install
npm install vuex -D
2、新建相关文件夹和文件
项目根目录src下新增store文件夹
sotre文件夹下新增index.js、getters.js、actions.js、mutations.js、types.js等文件
//注意index.js不是固定的,可以是其它名字,只是import store文件夹内容的时候默认会去找index.js
3、编写store相关内容
//types.js内容
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
//actions.js内容
import * as types from './types'
export default {
increment: ({
commit
}) => {
commit(types.INCREMENT);
},
decrement: ({
commit
}) => {
commit(types.DECREMENT);
},
clickOdd: ({
commit,
state
}) => {
if (state.mutations.count % 2 == 0) {
commit(types.INCREMENT);
}
},
clickAsync: ({
commit
}) => {
new Promise((resolve) => {
setTimeout(function() {
commit(types.INCREMENT);
}, 1000);
})
}
}
//getter.js
export default {
count: (state) => {
return state.count;
},
getOdd: (state) => {
return state.count % 2 == 0 ? '偶数' : '奇数'
}
}
//mutations.js
import {
INCREMENT,
DECREMENT
} from './types'
import getters from './getters'
const state = {
count: 20
};
const mutations = {
[INCREMENT](state) {
state.count++;
},
[DECREMENT](state) {
state.count--;
}
};
export default {
state,
mutations,
getters
}
//index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
import mutations from './mutations'
import actions from './actions'
export default new Vuex.Store({
modules:{
mutations
},
actions
});
4、引入store
在入口文件main.js引入store,注意这里默认找的是index.js,可以命名其它然后指定引用。
import store from './store/'
new Vue({
store,
el: '#app',
render: h => h(App)
})
5、使用vuex
在你需要用的vue文件引入,例如在App.vue。
<template>
<div id="app">
<h3>welcome vuex-demo</h3>
<input type="button" value="增加" @click="increment">
<input type="button" value="减少" @click="decrement">
<input type="button" value="偶数才能点击+" @click="clickOdd">
<input type="button" value="点击异步" @click="clickAsync">
<div>
现在数字为: {{count}}, 它现在是 {{getOdd}}
</div>
</div>
</template>
<script>
import {mapGetters, mapActions} from 'vuex'
export default{
computed:mapGetters([
'count',
'getOdd'
]),
methods:mapActions([
'increment',
'decrement',
'clickOdd',
'clickAsync'
])
}
</script>