ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Vue 中 store 基本用法

2022-05-08 18:01:36  阅读:271  来源: 互联网

标签:load Vue res getters 用法 state commit store


store是一个管理状态,在vuex中使用。

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({

state: {

//这里放全局参数

},

mutations: {

//这里是set方法

},

getters: { //这里是get方法,并且每次打开浏览器优先执行该方法,获取所有的状态 },

actions: {

// 处理state的方法体

},

modules: {

//这里是我自己理解的是为了给全局变量分组,所以需要写提前声明其他store文件,然后引入这里

}

})

store的执行顺序:
打开浏览器 → getters → 组件调用actions中的方法 → mutations(设置state的值) → getters(更新数据)
接着我直接从一个国外的项目,部分代码拷贝出来,进行详细解读。
首先这是一个组件,有个点击click事件。

onAddRow (data) {
const initVal = data.map((val, idx) => {
return {
colGrid: { span: val },
isCustom: 'btn-addCol'
}
})
this.addRow(initVal)
},

接着调用了actions里的方法,该方法的写法就很6,那个{}里的东西是由Vuex提供的,只是将Store里的数据提了出来

addRow ({ commit, state }, reload) {
let { layoutSections } = state
let _idx = layoutSections.length
let _newLaypout = [...layoutSections, reload]
// 调用set方法,set全局的state
commit(types.UPDATE_LAYOUT_SECTIONS, _newLaypout)
commit(types.UPDATE_ACTIVE_SECTION, _idx)
commit(types.UPDATE_ACTIVE_PROP, '')
},

我们直接看Store源码,就会发现:

function registerAction (store, type, handler, local) {
const entry = store._actions[type] || (store._actions[type] = []);
entry.push(function wrappedActionHandler (payload, cb) {
// 这里就是主要的参数,我们如果想要使用,就可以在{}里声明它
let res = handler.call(store, {
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state
}, payload, cb);
if (!isPromise(res)) {
res = Promise.resolve(res);
}
if (store._devtoolHook) {
return res.catch(err => {
store._devtoolHook.emit('vuex:error', err);
throw err
})
} else {
return res
}
});
}

通过debug

 

 

我们可以看到这个方法已经被编译成了这个样子,但是第一个参数,拥有的属性,就是上面源码中的参数。

 

 

这个方法传过来的值

 

 

接着,调用下面三个方法

 

 

上面的意思相当于

this.$store.commit('setDemoValue', value);

就会调用mutations的set方法

[types.UPDATE_LAYOUT_SECTIONS] (state, load) {
state.layoutSections = load
},
[types.UPDATE_ACTIVE_SECTION] (state, load) {
state.activeSection = load
},
[types.UPDATE_ACTIVE_PROP] (state, load) {
state.activeProp = load
},

调用完成后,执行getters更新状态

activeRow (state) {
debugger
let { layoutSections, activeSection } = state
return layoutSections[activeSection] || []
}

转自:https://blog.csdn.net/qq_41520636/article/details/121882632


标签:load,Vue,res,getters,用法,state,commit,store
来源: https://www.cnblogs.com/javalinux/p/16246260.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有