总结上图:vue
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex)
const store = new Vuex.Store({
})
new Vue({
el: '#app',
// 挂载后,全部的组件都会有一个$store
store
})
复制代码
// 实例化store对象申明数据
new Vuex.Store({
// state 管理数据
state: {
count: 100
}
})
// 在组件中使用:
<template>
<!--直接使用-->
<p>{{$store.state.count}}</p>
<!--经过计算属性使用-->
<p>{{count}}</p>
</template>
<script>
export default {
computed: {
count () {
return $store.state.count
}
}
}
</script>
复制代码
mapState
辅助函数帮助咱们生成计算属性import {mapState} from 'vuex'
export default {
data () {
return {
msg: 'XXX'
}
}
computed: mapState({
// 箭头函数
count: state => state.count,
// 传字符串参数'count' 等同于'state => state.count'
count: 'count',
// 在使用state中的数据时,若是依赖组件内部的数据,必须使用常规函数
count(state) {
return state.count + this.msg
}
})
}
复制代码
computed: mapState(['count']) --->至关于{count: function(state){return state.count}}
复制代码
computed: {
...mapState(['count'])
}
复制代码
// 实例化store对象申明: mutation必须同步执行
new Vuex.Store({
// state 管理数据
state: {
count: 100
},
// mutations 修改数据
mutations: {
increment(state) {
// 变动状态
state.count++
}
}
})
// 在组件中使用:
// 默认提交
methods: {
fn() {
//调用mutations中的increment
this.$store.commit('increment')
}
}
// 提交传参
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
复制代码
this.$store.commit('increment', {
amount: 10
})
复制代码
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
// 数组写法
...mapMutations([
'increment' // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
]),
// 对象写法
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
复制代码
// 在实例化store对象申明:
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
// actions 异步操做 获取后台数据
actions: {
getData (context) {
setTimeout(()=>{
// 数据获取成功
context.commit('increment')
},1000)
}
}
})
// 在组件中调用,也能够提交参数
this.$store.dispatch('getData')
复制代码
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'getData', // 将 `this.increment()` 映射为 `this.$store.dispatch('getData')`
]),
...mapActions({
add: 'getData' // 将 `this.add()` 映射为 `this.$store.dispatch('getData')`
})
}
}
复制代码