文章目录
- vuex
- state
- getters
- mutations
- actions
- actions和mutations的区别
- modules
vuex
vuex是一个专门为vue.js应用程序开发的状态管理模式+库,它采用集中式存储管理应用的所有组件的状态,并以响应的规则保证状态以一种可预测的方式发生变化
state
存放数据,类似与data
取state中的数据
方式一:
{{$store.state.a}}
方式二:
import {mapState} from 'vuex';
computed:{... mapState(['a'])//在html中直接使用
}
getters
store中的计算属性,类似于组件中的computed
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({state:{list:[{good_id:1,good_name:'鞋',good_num:3,goood_price:299},{good_id:2,good_name:'衣服',good_num:2,goood_price:499},]},getters:{//计算价格total(state){let obj={count:0,num:0}state.list.forEach(v=>{//总价obj.count+=v.goods_num+v.goods_price;//总数量obj.num+=v.goods_num;});return obj;}},mutations:{},actions:{},modules:{}
})
使用
{{total.num}}{{total.count}}
import {mapState} from 'vuex';
computed:{...mapGetters(['total'])
}
mutations
存放方法的,类似与methods
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({state:{a:1},mutations:{changeBtn(state){state.a='abc'}},actions:{},modules:{}
})
使用:
<template><div><h1>{{a}}</h1><button @click="changeBtn">按钮</button></div>
</template>
<script>
import {mapState,mapMutations} from 'vuex'
export default {computed:{...mapState(['a'])},methods:{...mapMutations(['changeBtn'])}
}
</script>
actions
actions类似与mutations,但是actions是通过commit直接提交mutations,它不是直接变更状态,可以包含任意异步操作
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({state: {list: [{ checked: true },{ checked: true },{ checked: true },{ checked: true },{ checked: true },{ checked: true },{ checked: true },{ checked: true }],selectList: []},getters: {checkAll (state) {return state.list.length == state.selectList.length}},mutations: {// 全选checkAll (state) {state.selectList = state.list.map(v => {v.checked = true})},// 全不选unCheckAll (state) {state.list.forEach(v => {v.checked = false});state.selectList = []}},actions: {// 购物车中的单选和全选checkedFn ({ commit, getters }) {//选中的情况下提交反选,反选的情况下提交选中getters.checkAll ? commit('unCheckAll') : commit('checkAll')}},modules: {}
})
<template><div><HeaderNavigation></HeaderNavigation><h1>This page is about</h1><ul><li v-for="(item, index) in list":key="index"><input type="radio":checked='item.checked'></li></ul><label for=""@click="checkedFn"><input type="radio":checked='checkAll'>全选</label></div>
</template><script>import HeaderNavigation from '@/components/HeaderNavigation.vue'
import { mapState, mapGetters, mapActions } from 'vuex'export default {components: {HeaderNavigation},computed: {...mapState(['list']),...mapGetters(['checkAll']),},methods: {...mapActions(['checkedFn'])}
}
</script><style>
body {margin: 0;
}
</style>
mapState、mapGetters放在组件中的computed中
mapMutations、mapActions放在组件中的methods中
actions和mutations的区别
actions提交的是mutation,而不是直接变更状态、
mutations 是同步的、actions可以包含任意的异步操作
modules
分成多个模块