1、在终端输入npm install vuex@3 --save
注意如果输入npm install vuex会安装vuex4版本,而vuex4只能在vue3中使用,因此安装vuex3才能在vue2中使用。
2、在main.js文件中引入
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store"; // 引入vuex
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
// 全局使用ElementUI
Vue.use(ElementUI);
Vue.config.productionTip = false;
new Vue({
router,
store, // 引入vuex
render: (h) => h(App),
}).$mount("#app");
3、在src下新建store文件夹和index.js文件
4、在index.js文件中插入以下示例代码,然后就可以在任意组件中使用了:
调用name变量:$store.state.name
调用mutations中定义的setName方法:this.$store.commit("setName", "Tom")
调用actions中定义的setNameByAxios函数:this.$store.dispatch('setNameByAxios')
// 在store里面的store.js文件写入
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);
// 集中管理多个组件共享的数据
export default new Vuex.Store({
// 共享数据
state: {
name: "rookig",
},
getters: {},
// 修改共享数据只能通过mutation实现,必须是同步操作
mutations: {
setName(state, name) {
state.name = name;
},
},
// 通过actions可以调用mutations,在actions中可以讲行异步操作
actions: {
// 通过context上下文参数,才能调用mutations中的对象
setNameByAxios(context) {
axios({
url: "/api/admin/employee/login",
method: "post",
data: {
username: "admin",
password: "123456",
},
})
.then((res) => {
if (res.data.code == 1) {
context.commit("setName", res.data.data.name);
}
})
.catch((error) => {
console.error("Error occurred:", error.response);
});
},
},
modules: {},
});