// src/store/index.js
import Vue from 'vue'
// import Vuex from 'vuex'
import Vuex from '@/vuex'

// 会默认调用 Vuex 的 install 方法

// Vue.use方法的简单实现
// Vue.use = function(plugin, options) {
//   plugin.install(Vue, options)
// }
Vue.use(Vuex)

// Vuex是一个对象,里面有一个大写的Store和install方法
export default new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    getCount(state) {
      return state.count + 1
    }
  },
  mutations: {
    changeCount(state, payload) {
      state.count += payload 
    }
  },
  actions: {
    changeCount({ commit }, payload) {
      setTimeout(() => {
        commit('changeCount', payload)
      }, 1000)
    }
  },
  modules: {
  }
})
// src/vuex/index.js
import { Store, install } from './store'

export {
  Store,
  install
}

export default {
  Store,
  install
}
// src/vuex/install.js
function vuexInit() {
  if (this.$options.store) {
    this.$store = this.$options.store // 给根属性添加 $store 属性
  } else if (this.$parent && this.$parent.$store) {
    this.$store = this.$parent.$store // 当前的组件去拿父组件的 $store 。如:根组件 -> 父组件 -> 子组件 -> 孙组件
  }
}

// 调用 install 方法后,需要将 store 属性分配所有组件,以便所有组件都能访问 store
export function applyMixin(Vue) {
  // install 执行就会让 mixin 执行,将 beforeCreate 合并到 Vue.options 上,子组件在渲染的时候会调用 beforeCreate
  Vue.mixin({
    beforeCreate: vuexInit
  })
}
// src/vuex/store.js
import { applyMixin } from './install'
export class Store {
  constructor(options) {

  }
}

export const install = (Vue) => {
  applyMixin(Vue)
}