搭建Vuex环境
步骤大纲
npm i vuex@3
,**Vue2** 使用版本 **3**,**Vue3** 可以不用加@3
- 在
components
下创建文件夹store
- 在
store
下创建index.js
脚本
- 在
main.js
中使用sotre
第一步 – store
import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex)
// 准备actions用于响应组件中的动作
const actions = { }
// 准备mutations用于操作数据 (state)
const mutations = { }
const state = { }
// 创建store
export default new Vuex.Store({
actions,
mutations,
state
})
由于Vuex
中的store
管理着三个模块
- actions
- mutations
- state
所以需要在store
中进行配置, 其中actions
接收一个动作,mutations
进行点单, state
是受操作的共享数据。
因为本质上
vue
是一个插件,所以我们在store
中使用Vue.use()
来使用了这个插件。
所以在
store>index.js
中我们需要引入Vue
和Vuex
就不难解释了。
第二部 – main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
el: '#app',
render: h => h(App),
store: store,
beforeCreate() {
Vue.prototype.$bus = this
}
})
在程序入口main.js
中引入store
,并在vm
中注册一个store
。