【Vue】搭建vuex环境

1、下载安装 vuex npm i vuex
2、创建 src/store/index.js 该文件用于创建 Vuex 中最为核心的 store

import Vue from 'vue'
import Vuex from 'vuex'	// 引入Vuex

Vue.use(Vuex)	// 应用Vuex插件

// 准备actions——用于响应组件中的动作
const actions = {

}

// 准备mutations——用于操作数据(state)		
const mutations = {

}
	
// 准备state——用于存储数据
const state = {
}			

// 创建并暴露store
export default new Vuex.Store({
	actions,
	mutations,
	state,
})

3、在 src/main.js 中创建 vm 时传入 store 配置项

import Vue from 'vue'
import App from './App.vue'
import store from './store'	// 引入store

Vue.config.productionTip = false

new Vue({
	el: '#app',
	render: h => h(App),
	store,										// 配置项添加store
	beforeCreate() {
		Vue.prototype.$bus = this
	}
})

过程:

  1. 安装插件并在 main.js 里面引用

只有写了前面那些配置项, vue 才会认识这个 store 的配置项,vm 上才会有

如果 vue 发现有不认识的配置项就会丢弃掉

扫描二维码关注公众号,回复: 14956206 查看本文章

发现组件和 vm 上都有了 $store

  1. 创建 store 文件夹, 里面建立 index.js

发现报错, 是因为,store 的创建位置不对

应该在在 vue.user(vuex)之后创建 store

原因分析

当这边引用我们在 store 里面 index.js 里面写的, 第十行引入时, 就把 store 的 index.js 里面的代码执行完毕了

也就是说此时都已经创建 store

然后再回到 main.js 里面创建 vue 即连 vue 实例都没有创建那 store 怎么放到 vm 上面

但是如果想当然就把 引用和使用的位置换一下. 一样报错

发现换了下位置跟前面报错一模一样

其实这是 vue 解析 import 的一个问题

这边正常引用

输出

把它顺序改变下

发现还是 import 优先调用

也就是对于 vue cli 来说, 它会优先扫描 import 的内容对 import 进行顺序执行

解决方法, 把这边的 vue.use(Vuex) 写到 store 文件夹的 index.js 文件夹上方, 在创建 store 前

store/index.js

src/main.js

然后我们观察 $sore 上面的值

有我们最想看到的 dipatch 和 commit

猜你喜欢

转载自blog.csdn.net/qq_37308779/article/details/125904019
今日推荐