programing

Vuex 돌연변이 및 작업이 작동하지 않음

prostudy 2022. 5. 30. 22:01
반응형

Vuex 돌연변이 및 작업이 작동하지 않음

Vue와 Vuex는 처음이라 저장소에서 데이터를 변환하는 방법을 찾고 있습니다.

현재 내 주(州)에서 기본 사용자 이름은 'default'이며, 이를 'oto'로 변경하고 싶습니다. 나중에 데이터베이스에서 이 정보를 가져옵니다.하지만 이해를 위해 난 그저 이 일이 잘 풀리도록 노력하고 있어.

이 시점에서 구성 요소가 올바르게 로드되고 '기본값'으로 표시됩니다.에러는 없다.

store.js:

// store.js 
export default {
    state: {
        username: 'default'
    },
    getters: {
    },
    mutations: {
        changeUsername (state) {
            state.username = 'otto'
        }
    },
    actions: {
        changeUsername (context) {
            context.commit('changeUsername')
        }
    }
}

vue 파일:

// Basic.vue
<template>
    <div>
        <p>{{ username }}</p>

    </div>
</template>

<script>
    import { mapState } from 'vuex';
    import { mapMutations } from 'vuex';
    import { mapActions } from 'vuex';


    export default {
        name: "basic",

        computed: {
            ...mapState([
                'username'
            ])
        },
        methods: {
            ...mapMutations([
                'changeUsername'
            ]),
            ...mapActions([
                'changeUsername'
            ])
        }
    }
</script>

당신의 돌연변이는 당신의 행동에 의해 불려질 것이기 때문에 포함시키지 마세요.버튼 클릭으로 액션을 호출합니다.예를 들어 다음과 같습니다.

스토어:

// store.js 
export default {
    state: {
        username: 'default'
    },
    getters: {
        username: state => state.username
    },
    mutations: {
        setUsername (state) {
            state.username = 'otto'
        }
    },
    actions: {
        updateUsername (context) {
            context.commit('setUsername ')
        }
    }
}

컴포넌트:

// Basic.vue
<template>
    <div>
        <p>{{ username }}</p>
        <button @click="updateUsername">Change!</button>
    </div>
</template>

<script>
    export default {
        name: "basic",

        computed: {
            username() {
                return this.$store.getters.username
            }
        },
        methods: {
            updateUsername() {
                this.$store.dispatch('updateUsername')
            }
        }
    }
</script>

추가 조언: 돌연변이와 행동에 이름을 붙일 때 주의하세요.원치 않는 행동을 피하기 위해 같은 이름을 사용하는 것을 원하지 않습니다.나는 보통 돌연변이의 이름을 짓는다.setXXXX그리고 나의 행동getXXX또는patchXXX요청 내용에 따라 달라집니다.

작업 jsfiddle

<template>
    <div>
        <p @click="changeUsername">{{ username }}</p>

    </div>
</template>

사용자가 p 태그를 클릭하면 사용자 이름을 변경할 수 있습니다.

언급URL : https://stackoverflow.com/questions/50969270/vuex-mutations-and-actions-not-working

반응형