1、安装
使用vue-cli搭建好项目以后,安装vuex npm install vuex –save-dev
2、创建Vuex.Store实例
文件夹目录如下:
main.js入口文件
import store from './store'
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
store/index.js:
import Vue from 'vue';
import Vuex from 'vuex';
import state from './state.js';
import getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';
import modules from './module/modules.js';
Vue.use(Vuex);
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
modules
});
export default store;
store/state.js
const state = {
count: 0,
number: 0,
username: 'liu',
nickname: 'never',
password: 123
};
export default state;
store/getters.js
const getters = {
message: state => {
return '用户名为:' + state.username;
},
msg: state => {
return `昵称为:${state.nickname}`;
// 等价于 return '昵称为:' + state.nickname;
// `${}` 是ES6中的模版字符串语法
}
};
export default getters;
store/mutations.js
const mutations = {
//同步增加
increment: state => {
state.count++;
},
//异步增加
asnyAdd: state => {
state.number++;
},
changePassword: (state, payload) => {
state.password = payload.password;
},
changeNickname: (state, payload) => {
state.nickname = payload.nickname;
}
};
export default mutations;
store/actions.js
const actions = {
asnyAdd: context => {
context.commit('asnyAdd');
},
changeNickname ({commit}, payload) {
commit('changeNickname', payload);
}
};
export default actions;
页面调用、修改状态
<template>
<div class="indexDemo">
<h1>{{study}}</h1>
<button @click="increment">同步加1</button>
<button @click="asnyAdd1">异步加1</button>
<button @click="changePassword({password: 123456})">同步修改密码</button>
<button @click="changeNickname({nickname: 'sleepwalker'})">异步修改昵称</button>
<p>count:{{count}}</p>
<p>number:{{number}}</p>
<p>username:{{username}}</p>
<p>nickname:{{nickname}}</p>
<p>password:{{password}}</p>
<p>{{message}}</p>
<p>{{msg}}</p>
</div>
</template>
<script>
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex';
export default {
name:'helloworld',
data() {
return {
study: 'vuex-study'
}
},
computed: {
...mapState(['count', 'number', 'username', 'nickname', 'password']),
...mapGetters(['message', 'msg'])
},
created(){
},
methods:{
...mapMutations(['increment', 'changePassword']),
// ...mapActions(['asnyAdd', 'changeNickname'])
//同上
...mapActions({
asnyAdd1:'asnyAdd',
changeNickname:'changeNickname'
})
},
watch:{
},
}
</script>