Vuex
vuex在使用时需要通过new Vuex.Store
获取到对应的对象,然后进行相关的配置
state
用来保存组件中的数据,如果想要修改这里的数据,需要通过mutation
进行修改
const store = new Vuex.Store({
state: {
msg: "Hello Vuex"
}
})
获取到对应state中的数据
在想要使用的组件中,我们可以直接通过this.$store.state.msg
获取到对应的msg数据
<template>
<div>
{{$store.state.msg}}
</div>
</template>
我们还可以在组件的computed中设置计算属性获取
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default {
computed: {
// 一般情况下,计算属性的名字和state中名字保持一致
msg () {
return this.$store.state.msg
}
}
}
</script>
我们还可以使用辅助函数mapState
来解决代码耦合问题
<template>
<div>
{{msg}}
{{otherName}}
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
computed: {
...mapState(['msg']),
...mapState({
otherName: 'msg'
})
}
}
</script>
mutations
mutation是用来修改state的唯一入口,mutation本质就是一个函数
const store = new Vuex.Store({
state: {
msg: "Hello Vuex"
},
mutations: {
setMsg (state, payload) {
state.msg = payload.msg
}
}
})
提交mutation
提交mutation需要借助$store.commit
方法
<template>
<div>
{{msg}}
{{otherName}}
<button @click="setMsg({msg: '新的内容'})">点击修改msg</button>
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
computed: {
...mapState(['msg']),
...mapState({
otherName: 'msg'
})
},
methods: {
setMsg (params) {
this.$store.commit('setMsg', params)
}
}
}
</script>
我们也可以使用辅助函数mapMutations
来解决一些问题
<template>
<div>
{{msg}}
{{otherName}}
<button @click="setMsg({msg: '新的内容'})">点击修改msg</button>
</div>
</template>
<script>
import {mapState, mapMutations} from 'vuex'
export default {
computed: {
...mapState(['msg']),
...mapState({
otherName: 'msg'
})
},
methods: {
...mapMutations(['setMsg'])
}
}
</script>
actions
action一般用来请求接口中的数据,action支持异步操作,但是action中的数据想要设置给state,必须通过mutation
const store = new Vuex.Store({
state: {
msg: "Hello Vuex"
},
mutations: {
setMsg (state, payload) {
state.msg = payload.msg
}
},
actions: {
getMsg ({commit}) {
相关请求函数().then(res => {
// res.data就是我们的值 需要commit给mutation
commit('setMsg', {msg: res.data})
})
}
}
})
action需要被dispatch
可以直接调用$store.dispatch方法
this.$store.dispatch('getMsg')
也可以使用辅助函数
import {mapActions} from 'vuex'
export default {
methods: {
...mapActions(['getMsg'])
},
created () {
this.getMsg()
}
}