浅谈Vuex的状态管理(全家桶)

2020-06-16 05:41:33易采站长站整理

<h5>{{count}}</h5>
<p>
<button @click="$store.commit('jia')">+</button>
<button @click="$store.commit('jian')">-</button>
</p>
</div>
</template>

<script>
import {mapState} from 'vuex'
export default{
name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
// 方法一
// computed: {
// count(){
// return this.$store.state.count + 6
// }
// }

// 方法二 需要引入外部 mapState
computed:mapState({
count:state => state.count + 10
})

// ECMA5用法
// computed:mapState({
// count:function(state){
// return state.count
// }
// })

//方法三
// computed: mapState([
// 'count'
// ])
}
</script>

7. mutations触发状态 (同步状态)


<template>
<div class="hello">
<h1>Hello Vuex</h1>
<h5>{{count}}</h5>
<p>
<button @click="jia">+</button>
<button @click="jian">-</button>
</p>
</div>
</template>
<script>
import {mapState,mapMutations} from 'vuex'
export default{
name:'hello', //写上name的作用是,如果你页面报错了,他会提示你是那个页面报的错,很实用
//方法三
computed: mapState([
'count'
]),
methods:{
...mapMutations([
'jia',
'jian'
])
}
}
</script>

8. getters计算属性

getter不能使用箭头函数,会改变this的指向

在store.js添加getters


// 计算
const getters = {
count(state){
return state.count + 66
}
}

export default new Vuex.Store({
state,
mutations,
getters
})
//count的参数就是上面定义的state对象
//getters中定义的方法名称和组件中使用的时候一定是一致的,定义的是count方法,使用的时候也用count,保持一致。
组件中使用

<script>
import {mapState,mapMutations,mapGetters} from 'vuex'
export default{
name:'hello',
computed: {
...mapState([
'count'
]),
...mapGetters([
'count'
])
},
methods:{
...mapMutations([
'jia',
'jian'
])
}
}
</script>

9. actions (异步状态)

在store.js添加actions


import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// 定义常量
const state = {
count: 1