vuex
快速上手
1 安装
npm i -D vuex
2 创建 store/index.js
3 快速上手vuex
// 初始化 store 实例,
import Vue from "vue";
import Vuex from 'vuex';
Vue.use(Vuex);
let store = new Vuex.Store({
})
export default store;
4 建立store实例与vue实例的联系,目的:为了在组件中 this.$store或者 store实例
// main.js
new Vue({
store, // 结果 this.$store ---> ./store/index.js导出的store对象
render:h=>h(App),
}).$mount('#app')
5 在组件中 验证 this.$store === store
vuex 是什么
vuex 是vue的状态管理工具,遵循单项数据流。实现了,多组件共同状态的管理。
vuex 中 state 是响应式数据。
vuex 解决了什么问题
- 1:组件数据通信,嵌套关系比较复杂。不利于传值
- 2:给关系型组件传值通信。
vux 中有有那些内容
state
state 表示vuex 中状态,存放,所有组件中共享的响应式数据
actions
actions 是异步的修改数据
- 1 监听 vueComponents 中异步行为,
- 2 通知 mutations,让Mutation 修改state
mutaions
- 同步修改state中数据
vuex的规则是什么
- 1:有一个state 就需要有一个 action mution
- 2: 修改过程
- 2.1 组件中通过 store.dispatch 触发 action
- 2.2 acion中通过 store.commit 触发mutaion
- 2.3 mution 中直接修改 state
- 3 当state 发生变化后,component 视图也会发生变化