Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。 就是用来存储所有共享的状态信息,通俗点来说就是 一个公共仓库
安装
npm install vuex --save
src 目录下新建 store 文件夹,创建 index.js文件引入、安装、创建并导出Vuex对象
import Vue from 'vue'
import Vuex from 'vuex'
//1.安装插件
Vue.use(Vuex)
//2.创建对象
const store = new Vuex.Store({
state:{} // 数据 this.$store.state
mutations:{} // 状态变更 this.$store.commit()
actions:{} // 异步操作 this.$store.dispatch()
getters:{} // 计算属性
})
//3.导出使用
export default store
// 模块(module)
const store = new Vuex.Store({
modules: {},
})
main.js 文件中挂载使用
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.use(Vuex)
new Vue({
el: '#app',
store,
render: h => h(App)
})
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
computed: { ...mapState({ }) }