<script>
/*
state
保存了组件的数据
如果想要在组件中使用msg这个数据,最简单的
直接
模板中{{$store.state.msg}}
函数中this.$store.state.msg
想要好看,则
computed: {
msg () {
return this.$store.state.msg // 其他地方就可以直接使用msg
}
}
getter 在组件中使用时和state方法类似,要把state改成getters
想要使用reverseMsg
直接
模板中{{$store.getters.reverseMsg}}
函数中this.$store.getters.reverseMsg
想要好看,则
computed: {
reverseMsg () {
return this.$store.getters.reverseMsg
}
}
mutation
mutation是一个函数,它的作用就是修改state,而且修改state只能通过这一个方式
我们如果想要在组件中对某个数据进行修改,则,直接提交对应的mutation即可
this.$store.commit('setMsg', '相关数据')
因为mutation要改变state,所以在mutation中有参数state和载荷payload
action
用法类似于mutation
一、给mutation传值需要commit
这是接受的操作
{
mutations: {
mutation函数 (state, payload) {
// 因为mutation改变的是state中的值,所以我们参数中有一个state方便我们快速改变对应的值
// payload接收commit处传递过来的数据
}
}
}
组件函数中提交mutation,就是给mutation传值
{
methods: {
函数 () {
this.$store.commit('mutation函数', 数据)
}
}
}
二、给action传值需要dispatch
this.$store.dispatch('action名字', 数据)
因为mutation是同步修改state,所以参数中有state
但是action是异步获取数据,获取后的数据想要修改到state,因此action中一定要提交mutation去修改state,所以在action的函数中有参数context,这个context就是一个store
如果想要提交,则context.commit('mutation中的函数名',传的值)
*/
const store = new Vuex.Store({
state: {
msg: '数据'
},
getters: {
reveseMsg () {
return msg.split('').revese().join('')
}
},
mutations: {
setMsg (state, payload) {
state.msg = payload
}
}
})
<!--
Vuex中常用的就
state mutations actions
如果我们想要在页面中渲染一些数据时,那么我们就可以把数据放在state中 state
如果我们要操作页面元素修改数据时,那么我们就要在事件处理函数中this.$store.commit('mutation') 提交mutation 让mutation去修改
如果我们要操作页面元素获取新的数据时,那么我们就要在事件处理函数中this.$store.dispatch('action') 然后在请求数据成功的时候,让action去commit('mutation') 然后mutation修改数据
action中的代码只涉及到,请求数据 提交mutation
mutation 只涉及到修改state
组件中设置到提交mutation或者分发action
-->
</script>
Vuex中的state、getters、mutations、actions
最新推荐文章于 2022-09-29 17:27:21 发布