1.简介
就是用来多组件共享数据的实现用的
2.使用VueX
因为使用的是vue2 所以下的是vuex3 若是vue3 必须下的是 vue4
npm i vuex@3
3.搭建环境
1.创建 src/store/index.js
//该文件用于创建一个Vuex中最为核心的store
//引入VueX
import Vuex from 'vuex'
import Vue from 'vue'
//准备 actions - 用于响应组件中的动作
const actions = {}
//准备 mutations - 用于操作数据(state)
const mutations = {}
//准备 state - 用于存储数据
const state = {}
Vue.use(Vuex)
//创建 store
const store = new Vuex.Store({
actions,
mutations,
state
});
//暴露store
export default store;
2.main.js引入
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入vue-resource
import vueResource from 'vue-resource'
//引入store
import store from './store/index'
//关闭Vue的生产提示
Vue.config.productionTip = false
//应用插件
// import plugins from './plugins'
//使用插件
// Vue.use(plugins,1,3,2,5,6)
// const d = Vue.extend({});
// Vue.prototype.eventBus= new d();
//使用插件
Vue.use(vueResource)
//创建vm
new Vue({
el: '#app',
render: (h) => h(App),//放入构造出 App组件模板
store,
beforeCreate() {
Vue.prototype.$bus = this; //安装全局事件总线
// console.log(this);
}
})
3.使用
store 下 建 index.js
//该文件用于创建一个Vuex中最为核心的store
//引入VueX
import Vuex from 'vuex'
import Vue from 'vue'
//准备 actions - 用于响应组件中的动作
const actions = {
jia(context,value){
console.log('actions中的jia被调用了',context ,value);
context.commit('JIA',value);
},
jian(context,value){
console.log('actions中的jian被调用了',context ,value);
context.commit('JIAN',value);
},
jiaOdd(context,value){
console.log('actions中的jiaOdd被调用了',context ,value);