Vue 搭建Vuex环境详解

作者:TA_WORLD 时间:2024-04-10 13:48:59 

目录
  • 搭建Vuex环境

  • 总结

搭建Vuex环境

src目录下创建一个文件夹store,在store文件夹内创建一个index.js文件

index.js用于创建Vuex中最核心的store


//  scr/vuex/index.js
// 引入Vuex
import Vuex from 'vuex'
// 用于响应组件中的动作
const actions = {}
// 用于操作数据
const mutations = {}
// 用于存储数据
const state = {}
// 创建store
const store = new Vuex.Store({
   actions,
   mutations,
   state
})
// 导出store
export default store

//  main.js
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import store from './store/index'
Vue.use(Vuex)
new Vue({
   render:h => h(App),
   store
}).$mount('#app')

但是这样会出现报错:

[vuex] must call Vue.use(Vuex) before creating a store instance

意思为:[vuex] 在创建 store 实例之前必须调用 Vue.use(Vuex)

原因:在我们导入store的时候,先执行引入文件的代码,所以在执行以下代码时,引入的文件已经被执行了

既然这样子,那么我们交换import store from './store/index'Vue.use(Vuex)两行代码

可是实际的结果是:[vuex] must call Vue.use(Vuex) before creating a store instance,依旧报错

原因:这是脚手架解析import语句的问题,会将import引入的文件提前,放在代码的最开始,也是最开始解析,然后解析本文件的代码

正确的写法:


//  scr/store/index.js
// 引入Vuex和Vue
import Vuex from 'vuex'
import Vue from 'vue'
// 应用Vuex插件
Vue.use(Vuex)
// 用于响应组件中的动作
const actions = {}
// 用于操作数据
const mutations = {}
// 用于存储数据
const state = {}
// 创建store
const store = new Vuex.Store({
   actions,
   mutations,
   state
})
// 导出store
export default store

//  main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
new Vue({
   render:h => h(App),
   store
}).$mount('#app')

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注!

来源:https://blog.csdn.net/qq_56303170/article/details/121325907

标签:Vue,搭建,Vuex
0
投稿

猜你喜欢

  • 基于Python和C++实现删除链表的节点

    2022-11-19 13:52:11
  • Response.Flush的用法

    2010-04-08 12:54:00
  • Go 实现热重启的详细介绍

    2024-04-25 15:06:15
  • 利用keras使用神经网络预测销量操作

    2022-02-25 05:48:31
  • Python函数式编程指南(三):迭代器详解

    2023-06-03 06:11:52
  • 如何利用Python打开txt格式的文件

    2022-06-01 02:08:36
  • Python使用smtplib模块发送电子邮件的流程详解

    2023-09-28 03:28:35
  • python 输入一个数n,求n个数求乘或求和的实例

    2022-06-06 01:44:36
  • python同步windows和linux文件

    2023-12-11 11:44:35
  • vue实现添加标签demo示例代码

    2024-05-21 10:14:49
  • Django显示可视化图表的实践

    2023-04-13 02:42:38
  • 对Keras中predict()方法和predict_classes()方法的区别说明

    2022-11-05 09:13:32
  • Go语言算法之寻找数组第二大元素的方法

    2023-06-24 16:19:03
  • Python编程中对文件和存储器的读写示例

    2022-04-27 06:26:35
  • 3个适合新手练习的python小游戏

    2023-08-02 02:12:27
  • python应用文件读取与登录注册功能

    2023-04-17 17:04:03
  • 页面重构中的模块化思维

    2009-06-28 15:36:00
  • Python使用sftp实现传文件夹和文件

    2021-09-30 12:27:37
  • Golang 实现Socket服务端和客户端使用TCP协议通讯

    2023-07-21 10:09:38
  • 一个Access数据库数据传递的实例方法

    2008-11-28 16:24:00
  • asp之家 网络编程 m.aspxhome.com