1、创建项目
vue create test_vuex
2、安装vuex
npm i vuex@3
tips:vue2默认使用的vuex为vuex3版本,vue3使用的vuex为vuex4版本,所以需要指定版本安装
3、在main.js引入vuex
import vuex from 'Vuex'
Vue.use(Vuex)
4、src目录下创建store文件夹,用于管理vuex,store文件下创建index.js
5、创建vuex实例
const store = new Vue.Store({
})
vuex实例的配置对象为store管理的方法
import Vuex from 'vuex'
// 响应组件中的动作
const actions = {}
// 操作数据
const mutations = {}
// 存储数据
const state = {}
const store = new Vuex.Store({
actions,
mutations,
state
})
export default store
6、main.js文件引入store
import store from './store/index.js'
new Vue({
el:'#app',
store,
render: h => h(App),
})
7、此时运行文件会报错
报错原因:因为在创建vuex实例的时候用到了vuex,但此时vuex在main.js文件引入,没有在index.js引入。
解决办法:在index.js引入vuex即可