一.介绍
1.定义:Vuex是vue框架中状态管理。Vuex 也集成到 Vue 的官方调试工具 devtools extension ,是把组件的共享状态抽取出来,以一个全局单例模式管理。在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!这就是“状态管理模式”。
-
2.应用场景:单页面的应用
- 实现购物车功能
- 下单页面有选择优惠券按钮,点击进入优惠券页面,选择后返回到下单页,数据会绑定回来,显示已选择的优惠券;
- 登录状态
3.vuex数据流
<img src='./images/vuex数据流.png' />
二.使用步骤
1.安装:
vue add vuex
2.引入安装好的vuex和vue
import Vuex,{Store} from 'vuex'
3.使用use注册vuex
Vue.use(Vuex)
4.实例化vuex
export default new Store({
state:{
count:0
},
mutation:{
add(state,value){
state.count+=value
}
},
action:{
},
getters:{
}
})
-
6.配置vuex的核心属性
state:相当于data(私有的),state是公有的,存放数据,在页面中读取数据:$store.state.属性名
它通过mapState
把全局的 state 和 getters 映射到当前组件的 computed 计算属性中
mutations:相当于methods(私有的),mutations是公有的,修改局部数据
改变store的状态
在mutations中,只能执行同步操作其中两个参数:state是自带,obj是传入的,obj={type:'',value:''}
store/index.js: mutations:{ add(state,obj){ state.count +=obj.value }, sub(state,obj){ state.count -=obj.value } } Home.vue中: //辅助函数 import {mapState,mapMutations} from 'vuex' methods:{ add(){ <!-- this.$store.commit({ type:'add', value:'3' }) --> ...mapMutations{ sub:{ type:'sub', value:'3' } } } }
- actions:用于异步发送请求,默认参数是context是一个对象,包含commit和state两个属性
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。Action 通过store.dispatch
方法在组件的生命周期created中触发:
store/index.js: actions:{ getTodo({commit}){ axios.get('http://jsonplaceholder.typicode.com/todos').then(res => { console.log(res) commit('getTodo',res.data) //store.commit 传入额外的参数,即 mutation 的 载荷(payload) }) } } 在组建中:通过生命周期函数created触发该请求, created(){ this.$store.dispatch('getTodo') } 将得到的数据存到state中,需要mutations修改,在mutations中调用: getTodo(state,data){ //store.commit 传入额外的参数,即 mutation 的 载荷(payload) state.todos=data } 在state中用todos接收数据 todos:[]
- getters:相当于computed和filter的结合
store/index.js: getters:{ getCount(state){ return state.count + '~~~~' } } 在组件中,触发该方法 <h2>{{$store.getters.getCount}}</h2>
- modules :设置每一个模块,包括state,mutations... 开启命名空间,控制各自模块的数据
namespaced:true
7.暴露
8.在main.js中引入store 并挂载到vue上
-
9.获取数据的方法
- 可以在任意的组件通过
$store.state.属性名
获取state的数据
<h2>{{$store.state.count}}</h2>
- 使用computed计算获取
<h2>{{count}}</h2> computed:{ count(){ return this.$store.state.count } }
- 通过辅助函数获取
<h2>{{count}}</h2> import { mapState } from 'vuex' computed:{ ...mapState(['count']) }
- 可以在任意的组件通过
10.通过
$store.commit
方法触发状态变更11.由于 store 中的状态是响应式的,在组件中调用 store 中的状态简单到仅需要在计算属性中即computed返回即可。触发变化也仅仅是在组件的 methods 中提交 mutation。