在vue中,常见的状态管理仓库就是vuex,接下来简单记录一下用法。
1、下载安装
npm install vuex@next --save
2、在src下新建store文件夹,文件夹下有index.js文件和独立的仓库模块文件。在index中编写代码
import Vue from "vue";
import Vuex from 'vuex';
import countNum from './countModules/index.js' // 引入的计数的仓库
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
countNum // 将单独的仓库统一放在modules中导出
}
})
3、编写计数仓库代码
4、在main.js中挂载store到全局
5、使用
// 使用变量
this.$store.state.countNum.number
// 改变变量
this.$store.dispatch('actionChangeNum')
6、map辅助函数
-
mapState({})从state中取值 -
mapActions([])映射出actions中的函数 -
mapGetters([])映射出getter中的函数
7、思想讲述
组件通过
dispatch 调用 actions, actions通过 commit 调用Mutations,Mutations触发state更新后,通过调用render改变组件视图