1、先看一个vue响应式的例子,vue中的data 、methods、computed,可以实现响应式。
视图通过点击事件,触发methods中的increment方法,可以更改state中count的值,一旦count值发生变化,computed中的函数能够把getCount更新到视图。
<div id="app">
<button @click="increment"></button>
{{getcount}}
</div>
new Vue({
el: "#app",
// state
data () {
return {
count: 0
}
},
// view
computed: {
getCount(){
return this.count
}
},
// actions
methods: {
increment () {
this.count++
}
},
})
2、我们可以用vuex实现和vue同样的响应式功能。
其实他们原理时一样的,vuex中也有四个属性值:state、getters、mutations、actions。。
在没有actions的情况下:
数据:state --> data
获取数据:getters --> computed
更改数据:mutations --> methods
视图通过点击事件,触发mutations中方法,可以更改state中的数据,一旦state数据发生更改,getters把数据反映到视图。
那么actions,可以理解处理异步,而单纯多加的一层。
既然提到了mutions actions这时候 就不得不提commit,dispatch这两个有什么作用呢?
在vue例子中,通过click事件,触发methods中的方法。当存在异步时,而在vuex中需要dispatch来触发actions中的方法,actions中的commit可以触发mutations中的方法。同步,则直接在组件中commit触发vuex中mutations中的方法。
下面我们看下vuex中能像vue中实现改变状态,更新视图的功能:
Vuex.js
const store = new Vuex.Store({
state: {
count: 0
},
//state的值只能通过mutations来修改
mutations: {
increment(state) {
state.count++
}
},
//this.$store.commit("increment")触发mutations中函数"increment"
actions: {
increment({commit}) {
commit("increment"); //this.$store.commit("increment")
}
},
//通过getter中的方法来获取state值
getters: {
getCount(state) {
return state.count
}
}
})
export default store
App.vue
<template>
<div id="app">
<button @click="increment">增加</button>
<!-- 有时候不能直接 强制使用store里面的状态 this.$store.state.count -->
{{this.$store.getters.getCount}}
</div>
</template>
<script>
export default {
methods: {
increment(){
//this.$store.dispatch("increment")触发actions函数"increment"
this.$store.dispatch("increment")
}
}
}
</script>