1.安装vuex
$ npm install vuex --save
2.在src目录下新建store文件和store.js
3.store.js
// store.js
import Vue from 'vue'
import VueX from 'Vuex'
Vue.use(VueX);
const store = new VueX.Store({
//state属性用来存储状态值
state: {
count: 0,
name: ''
},
//getters属性用来获取状态值,相当于SPA页面中的computed属性
getters: {
count: function (state) {
return state.count;
},
name: function(state) {
if(state.name == 'doinb'){
state.name= 'doinb6'
return state.name
}
}
},
//mutations用来提供改变状态的方法,只能执行同步方式
mutations: {
increment: function (state) {
state.count ++;
},
decrement: function (state) {
if (state.count == 0) {
state.count = 0;
} else {
state.count --;
}
},
changeName1(state, name) {
state.name = name
},
changeName2(state, name) {
state.name = name
}
},
//actions接收对应的指令,去mutations中执行,能够执行异步方式
actions: {
changeName2(context, name) {
setTimeout(() => {
context.commit("changeName2", name);
}, 3000)
},
}
})
export default store;
4.在项目入口文件引入store.js,记住别忘记在vue实例下注册store
5.demo.vue
<!-- vuex -->
<template>
<div>
<h1>{{name}}</h1>
<button @click="decrement"> - </button>
<input type="text" v-model="count">
<button @click="increment"> + </button>
</div>
</template>
<script>
export default {
data() {
return {};
},
computed: {
name() {
// return this.$store.getters.name; // getters方式获取值
return this.$store.state.name;
},
count() {
return this.$store.state.count;
}
},
components: {},
mounted() {},
methods: {
increment() {
this.$store.commit("increment");
this.changeName1();
},
decrement() {
this.$store.commit("decrement");
this.changeName2();
},
changeName1() {
this.$store.commit("changeName1", '叫我官人'); //mutations 方式
},
changeName2() {
this.$store.dispatch("changeName2", 'doinb'); // actions 方式
}
}
};
</script>
<style scoped>
</style>