首先安装vuex -->
npm install vuex --save
主要用的方法
import {mapGetters, mapMutations, mapActions} from 'vuex';
下面我自己做的几个简单的学习小例子,一起学习下。
1 首先新建目录store
2-1
state.js -->初始数据 --
const state = {
name: 'weish',
age: 22,
liyuefeng:'李越峰',
count:6
};
export default state;
2-2
getters.js-->获取数据
export const name = (state) => {
return state.name;
}
export const age = (state) => {
return state.age
}
export const other = (state) => {
return `My name is ${state.name}, I am ${state.age}.`;
}
export const liyuefeng = (state) => {
return state.liyuefeng
}
export const count = (state) => {
return state.count
}
2-3
mutations.js ----->异步修改数据
export default {
//与下方 commit 中的 ‘increment' 相对应
increment(state){
state.count ++;
},
increments(state){
state.count --;
},
fun(state, changName){
state.name = changName.myName;
}
};
2-4
actions.js 同步修改数据
export default {
increment({
commit,
state
}) {
//提交一个名为 increment 的变化,名字可自定义,可以认为是类型名,与上方 mutations 中的 increment 对应
//commit 提交变化,修改数据的唯一方式就是显式的提交 mutations
commit('increment')
},
increments({
commit,
state
}) {
//提交一个名为 increment 的变化,名字可自定义,可以认为是类型名,与上方 mutations 中的 increment 对应
//commit 提交变化,修改数据的唯一方式就是显式的提交 mutations
commit('increments')
},
fun({commit},date){
commit('fun', {myName: date});
}
};
2-5
index.js 引入-配置
import vue from 'vue';
import vuex from 'vuex';
import state from './state.js';
import * as getters from './getters.js';
import mutations from './mutations.js';
import actions from './actions.js';
import createLogger from 'vuex/dist/logger'; // 修改日志
vue.use(vuex);
const debug = process.env.NODE_ENV !== 'production'; // 开发环境中为true,否则为false
export default new vuex.Store({
state,
getters,
mutations,
actions,
plugins: debug ? [createLogger()] : [] // 开发环境下显示vuex的状态修改
});
3 main.js引入
import store from './store/index.js';
new Vue({
el: '#app',
store,
router,
components: { App },
template: '<App/>'
})
4 新建组件
<template>
<div class="hello">12
<button-counter ></button-counter>
<button @click="fun">按钮</button>
{{name}}{{age}}{{other}}{{liyuefeng}}{{count}}
<button @click="increment">增加</button>
<button @click="increments">减少</button>
<h1>{{count}}</h1>
</div>
</template>
<script>
import buttonCounter from './buttonCounter.vue'
import {mapGetters, mapMutations, mapActions} from 'vuex';
export default {
data () {
return {
msg: 'Welcome to Your Vue.js App',
}
},
computed: {
...mapGetters([
"name",
"age",
"other",
"liyuefeng",
"count"
])
},
components:{
buttonCounter
},
methods: {
//mapMutations mapActions`
...mapActions([
//该 increment 来自 store.js 中导出的 actions 和 mutations 中的 increment
'increment',
"increments",
"fun"
]),
//如果需要向actions里面传值就手动调用
fun(){
this.$store.dispatch('fun',this.msg);
}
//...mapActions(['fun'])== this.$store.dispatch('increment');
}
}
</script>