首页 文章

Vuex突变和行动不起作用

提问于
浏览
4

我是Vue和Vuex的新手,我正在试图弄清楚如何在商店中改变数据 .

目前在我的状态下,默认用户名是'default',我想将其更改为'otto',稍后会从数据库中获取此信息 . 但为了理解我只是想让它发挥作用 .

此时组件正确加载,并显示“默认” . 没有错误存在 .

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>

2 回答

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

    如果用户点击p标签,您可以更改用户名 .

  • 0

    不要包含您的突变,因为它会被您的操作调用 . 然后在按钮单击上调用操作:

    商店:

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

    Additionnal advice: 在命名突变和行动时要小心 . 您不希望它们具有相同的名称以避免不必要的行为 . 我通常根据请求的名称命名我的变异 setXXXX 和我的动作 getXXXpatchXXX .

    Working jsfiddle

相关问题