vuex是一个专门为vuejs设计的集中式状态管理架构。状态简单来说就是data中需要共用的属性。
1、引入vuex
利用npm install vuex --save
2、x新建一个store文件夹,并在文件夹下面新建一个store.js文件,文件中引入我们的vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
3、使用vuex,引入之后用Vue.use进行引用
Vue.use(Vuex)
4、在mainjs中引入新建的store文件
import storeConfig from ‘./vuex/store’
5、在实例化Vue对象时加入store对象
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
demo实例:
1、 store.js
const state = {
count:1
}
2、用export default 封装代码,让外部可以引用
export default new Vuex.store({
state
})
3、新建一个vue模板,位置在components文件夹下,名字叫count.vue,在模板中引入我们刚健的storejs文件 ,并在模板中用{{$store.state.count}}输出count的值
<template>
<div>
<h2>{{msg}}</h2>
<hr/>
<h3>{{$store.state.count}}</h3>
</div>
</template>
<script>
import store from '@/vuex/store'
export default{
data(){
return{
msg:'Hello Vuex',
}
},
store
}
</script>
4、在storejs中加入两个改变state的方法
const mutations = {
add(state){
state.count+=1
},
reduce(state){
state.count-=1
}
}
mutations里面写改变state数值方法
5、在count.vue模板中加入两个按钮,并调用mutations中的方法
<div>
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>
state访问状态对象
状态对象赋值给你不对象,也就是把store中的值,赋值给我们模板中data的值:
1、通过computed的计算属性直接赋值
commputed属性可以在输出前,对data中的值进行改变,赋值给我们模板里的data中的值。
computed:{
count(){
return this.$store.state.count
}
}
2、通过mapState的对象来赋值
我们首先用import引入mapState
import {mapState} form 'vuex'
在computed计算属性里:
computed:mapState({
count:state=>state.count
})
3、通过mapState的数组来赋值
computed:mapState(['count'])
Mutations修改状态($store.commit())
Vuex提供了commit方法来修改状态
模板获取Mutations方法
1、在模板 中count.vue里用import引入我们的mapMutations
import {mapState,mapMutations} from 'vuex'
2、在模板的<script>标签里添加methods属性,并加入mapMutations
methods:mapMutations([
'add','reduce'
])
通过上边两部,可以在模板中直接使用: <button @click="reduce">-</button>
getters计算过滤操作
const getters = {
count:function(state){
return state.count+=100
}
}
export default new Vuex.store({
state,mutations,getters
})
在vue构造器里只能有一个computed属性,如果写多个,只有最后一个computed属性可用,改造用ES6的展开运算符'...'
computed;{
...mapState(["count"]),
count(){
return this.$store.getters.count;
}
}
用mapGetters简化模板写法
首先用import引用我们的mapGetters
import {mapState,mapMutations,mapGetters} from 'vuex'
在computed属性中加入mapGetters
...mapGetters(['count'])
actions异步修改状态
actions和mutations功能是一样的,不同的是actions是异步的改变state状态,而Mutations是同步的改变状态。
在storejs中声明actions
actions是可以调用Mutations里的方法的
const actions= {
addAction(context){
context.commit('add',10)
},
reduceAction({commit}){
commit('reduce')
}
}