Vuex中的state、getters、mutations、actions

<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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值