七、vuex的使用
1)安装
cnpm i vuex -S
2)配置
// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
// 使用组件
Vue.use(Vuex)
export default new Vuex.Store({
// 存放状态(数据)
state: {
num: 1
},
getters: {},
// 修改state数据
mutations: {},
// 处理异步请求
actions: {}
})
3)注册
// src/main.js
import Vue from 'vue'
import App from './App.vue'
// 引入配置好的vuex
import store from '@/store';
Vue.config.productionTip = false
let a = 10;
new Vue({
render: h => h(App),
// 注册vuex
store,
}).$mount('#app')
4)使用
- 在组件中获取state数据以及派发、提交其action、mutation
<template>
<div>
<h1>计数器</h1>
<h2>当前vuex中的num为:{{ num }}</h2>
<h2>增量:<input type="number" v-model="value"></h2>
<button @click="increment">增加</button><button @click="incrementAsync">异步增加</button>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: "App",
data() {
return {
value: 1
}
},
computed: {
// 映射vuex中的num给当前组件计算属性的num
...mapState({
num: state => state.num
})
},
methods: {
increment() {
// 提交mutation
this.$store.commit("INCREMENT", this.value)
},
incrementAsync() {
// 派发action
// this.$store.dispatch("incrementAsync", this.value)
// action中返回promise时可进行then、catch操作
this.$store.dispatch("incrementAsync", this.value).then((data) => {
console.log(data)
}).catch((err) => {
console.log(err)
});
}
},
};
</script>
<style>
</style>
- 其中vuex中的配置如下:
import Vue from 'vue';
import Vuex from 'vuex';
// 使用组件
Vue.use(Vuex)
export default new Vuex.Store({
// 存放状态(数据)
state: {
num: 1
},
getters: {},
// 修改state数据
mutations: {
INCREMENT(state, payload) {
state.num += payload * 1
}
},
// 处理异步请求
actions: {
incrementAsync({ commit }, payload) {
// 异步操作模拟发送请求
// setTimeout(() => {
// commit("INCREMENT", payload)
// }, 1000)
// 也可返回promise进行其他操作
return new Promise((resolve, reject) => {
try {
setTimeout(() => {
commit("INCREMENT", payload)
resolve("成功")
}, 1000)
} catch (error) {
reject(error)
}
})
}
}
})