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] || []
}小结
vue里store的用法是什么
vuex 是一个专为 vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
每一个 vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。vuex 和单纯的全局对象有以下两点不同:
vuex 的状态存储是响应式的。当 vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
到此这篇关于vue 中 store 基本用法的文章就介绍到这了,更多相关vue store 用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论