1 安装 Vuex
安装之前需要了解一个版本问题,在 vue2 中,要用 vuex 的 3 版本,在 vue3 中,要用 vuex 的 4 版本,要严格遵循这个版本要求,不然就会出现各种意想不到的问题,例如下方安装报错,就算因为版本问题
安装的方式也有好几种,我这里采用的是 npm 安装
npm
npm install vuex@next --save
复制代码
Yarn
yarn add vuex@next --save
复制代码
我这里用的是 vue2,所以就安装 vuex 的 3 版本,打开终端,输入:
2 使用 Vuex
安装完成之后,就可以 import 和 use 了,这里 Vuex 的 v 大小写都可以,官网文档是大写的,非要小写也没错,只是一个命名的问题
// 引入Vueximport Vuex from 'vuex'// 使用VuexVue.use(Vuex)
复制代码
3 使用虚拟 store
到了 use 完 Vuex 这一步后,然后创建 vm 或者 vc 的时候就可以传入 store 这个配置项了
这样就实现了让每一个 vc 实例都有一个 store 对象了,但是现在的 store 里面的值都是假的,所以现在要创建(封装)真实的 store
4 创建 store
想创建 store 有两种做法
第一种做法
可以在项目的 src 目录创建一个文件夹叫做 vuex,然后在里面新建一个 store.js,这样别人一看就知道用到了 vuex 技术,并且 store 在这里创建的,虽然这种方式清晰明了,但是不是官方推荐的
第二种做法
在项目的 src 目录创建一个叫 store 的文件夹,并且创建 index.js,虽然没有体现 vuex,但是在 src 里面看到 store,就相当于看到了 vuex,这种方式也是官网推荐的
这两种方式都行,但是官网推荐的是第二种做种,所以这里我采用的是第二种做法
5 暴露(导出)store
在 index.js 写入相关代码
// 该文件用于创建Vuex中最为核心的store
// 引入Vueximport Vuex from 'vuex'
// 准备actions 用于相应组件中的动作const actions={}// 准备mutations 用于操作数据(state)const mutations={}// 准备state 用于存储数据const state={}// 创建并暴露(导出)store export default new Vuex.Store({ // 准备store里面的三大元素 这里key和value重名,可以使用简写形式 比如:action,mutations,state 这里我不想采用简写形式 actions:actions, mutations:mutations, state:state})
复制代码
6 引入并使用真实 store
既然真实的 store 以及准备完了,我们就可以引入真实的 store 并且替换掉上面我们写的假的 store 了
这里 store 触发了简写形式,但是我没有省略,个人不习惯这种简写
这样一个真实的 store 就被创建配置完成并引用了,vc 或者 vm 实例身上都有一个 store 对象了
7 解决脚手架解析 import 语句的问题
看似基本工作都做完了,但是查看浏览器报错了,看似是一个前后调用问题,实际上是一个脚手架解析 import 语句的问题
[vuex] must call Vue.use(Vuex) before creating a store instance.
复制代码
这时候我们可以换一种思路,把 use 写道 index.js 里面,让 main.js 只需要引入以及准备好的 store
这时候再次查看 store,发现错误消息并且每个 vc 或者 vm 都有一个真实的 store
并且看到的 dispatch 和 commit 等相关 api,这就意味着可以和 vuex 进行操作了
到这就完成了搭建 Vuex 的开发环境了,也就是意味着可以使用 vuex 了 代码如下:
index.js
// 该文件用于创建Vuex中最为核心的store
// 引入Vueimport Vue from 'vue'// 引入Vueximport Vuex from 'vuex'// 使用VuexVue.use(Vuex)// 准备actions 用于相应组件中的动作const actions={}// 准备mutations 用于操作数据(state)const mutations={}// 准备state 用于存储数据const state={ sum:0 //总和}// 创建并暴露(导出)store export default new Vuex.Store({ // 准备store里面的三大元素 这里key和value重名,可以使用简写形式 比如:action,mutations,state 这里我不想采用简写形式 actions:actions, mutations:mutations, state:state})
复制代码
main.js
// 引入Vueimport Vue from 'vue'// 引入Appimport App from './App.vue'// 引入storeimport store from './store/index'// 关闭Vue的生产提示Vue.config.productionTip=false// 创建vm const vm=new Vue({ el:'#app', render:h=>h(App), store:store, beforeCreate(){ Vue.prototype.$bus=this } })
复制代码
8 搭建 vuex 环境总结
1 创建文件:src/store/index.js
//引入Vue核心库import Vue from 'vue'//引入Vueximport Vuex from 'vuex'//应用Vuex插件Vue.use(Vuex)
//准备actions对象——响应组件中用户的动作const actions = {}//准备mutations对象——修改state中的数据const mutations = {}//准备state对象——保存具体的数据const state = {}
//创建并暴露storeexport default new Vuex.Store({ actions, mutations, state})
复制代码
2 在main.js中创建 vm 时传入store配置项
......//引入storeimport store from './store'......
//创建vmnew Vue({ el:'#app', render: h => h(App), store})
复制代码
评论