0
点赞
收藏
分享

微信扫一扫

Vue学习笔记:Vuex Part02 Mutation

蓝莲听雨 2023-08-16 阅读 65

Mutation

主要用于处理同步状态请求 

Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数

const store = createStore({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    },
    setcount(state,payload){
    state.count = payload.value
    }
  }
})

对于mutation处理函数,不能直接调用,需要以相应的 type 调用 store.commit 方法:

store.commit('increment')

提交载荷Payload

向 store.commit 传入额外的参数,即 mutation 的载荷(payload):

store.commit('setcount', {
  value: 5
})

使用对象风格提交commit

store.commit({
  type: 'setcount',
  value: 5
})

示例

使用点击事件演示

一个按钮实现count+1 一个按钮实现将count设定为input中数字,分别对应两个mutations方法


store/index.js

import { createStore } from 'vuex'

const store = createStore({
    state() {
        return {
            count: 0
        }
    },
    mutations: {
        increment(state) {
            state.count++
        },
        setcount(state, payload) {
            console.log(payload)
            state.count = payload
        }
    },
})
export default store

app.vue

<template>
    <div>
        count - {{ count }}
    </div>
    <div>
        <button @click="handleIncrement">count+1</button>
        <div>
            <input v-model.number="setcount">
            <button @click="handleset">set</button>
        </div>

    </div>
</template>
<script>
export default {
    data() {
        return {
            setcount: 5,
        }
    },

    methods: {
        handleIncrement() {
            this.$store.commit(
                'increment',
            )
        },
        handleset() {
            console.log(this.setcount)
            this.$store.commit(
                'setcount', parseInt(this.setcount))
            console.log(this.$store.state.count)
        }
    },
    computed: {
        count() {
            return this.$store.state.count
        }
    }
}
</script>

Vue学习笔记:Vuex Part02 Mutation_mutation

举报

相关推荐

0 条评论