说在前面:一直想学vuex但碍于没有实践项目,且用vue里的父子组件传值也能解决需要,刚好接到一个需求用的是vuex,所以快速学习vuex。学习vuex能共享状态,方便各个组件间共享状态,尤其对于嵌套层级深的组件间的状态共享具有重要意义
废话不多说,直接看一份vuex的存储文件~麻雀虽小,五脏俱全:
import Vue from 'vue' //引入vue
import Vuex from 'vuex' //引入vuex
import axios from 'axios' //引入axios用于发异步请求
Vue.use(Vuex);
const state = { //统一状态管理
platformId: 0,
versionList: [],
commentCount: 0,
}
const mutations = { //一般只用于对state里定义的状态值更改
setPlatformId(state, value) {
state.platformId = value
},
setVersionList(state, list) {
state.versionList = list;
},
}
const getters = { //用于状态进行计算
//此方法用于格式化评论数,如3000转化成3,000
formatedCommentCount: ({commentCount}) => {
let re = /\d{1,3}(?=(\d{3})+$)/g;
let n1 = String(commentCount).replace(/^(\d+)((\.\d+)?)$/, (s, s1,s2) => (s1.replace(re, "$&,") + s2));
return n1;
},
const actions = { //用于异步操作,要有提交到mutation的操作
getVersionList(context, plat) {
axios.get(url, {
params: {
opeaCode: 'GetVersList',
plat: 3}
})
.then(function (response) {
let data = response.data;
context.commit('setVersionList', data)}) //提交到mutation方法,以改变状态
.catch(function (error) {
console.log(error);});
}
},
export default new Vuex.Store({
state,
mutations,
getters,
actions
})
一份store文件建立好了,如何在组件内引用呢?示例如下:
import store from "@/vuex/store"; //引入前面建立好的store文件,地址自定
import { mapState, mapMutations, mapGetters, mapActions } from "vuex"; //引入辅助函数,详情官网
export default {
store,
data: () => {
return {};
},
computed: {
...mapState([
"platformId", //将该组件中需要用的状态添加进来
]),
...mapGetters(["formatedCommentCount"])
},
methods: {
...mapActions([ "getVersionList"]),
...mapMutations([
"setPlatformId",
])
}
这样你就可以正常像vue一样,正常使用这些引入的方法,或状态啦~
网友评论