0. Vuex
Vuex 是什么?
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
Vuex 统一管理状态的好处是什么?
- 能够在Vuex中集中管理共享的数据,便于开发和维护
- 高效地实现组件之间的数据共享,提高开发效率
- 存储在Vuex中的数据都是响应式的,能够保持数据与页面的同步
Vuex 的基本使用
1. 安装 Vuex 依赖包
npm install vuex -save
npm i vuex -S
2. 导入 Vuex 包
store.js 文件中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
3. 创建 store 对象
store.js 文件中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = nwe Vuex.Store({
// state 中存放全局共享的状态
state: {}
})
4. 将 store 对象挂载到 Vue 实例中
main.js 文件中
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
el:'#app',
/**
* 将创建的共享状态对象,挂载到 Vue 实例中
* 所有的组件,就可以直接从 store 中获取共享的状态了
*/
store,
router,
render: h => h(App)
})