programing

.vue 컴포넌트 분리/준비함수에서 vuex 액션을 명시적으로 호출합니다.

itsource 2022. 7. 14. 20:44
반응형

.vue 컴포넌트 분리/준비함수에서 vuex 액션을 명시적으로 호출합니다.

내 프로젝트에서 vue-js와 vuex를 시도하고 있어.

정의했습니다.store.js:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

const state = {
    user: {}
};

const mutations = {
    SET_CURRENT_USER (state, data) {
        state.user = data;
    }
};

export default new Vuex.Store({
    state,
    mutations
});

그리고 나의actions.js:

export const readCurrentUser = function({dispatch, state}) {
    let api = require('../api/resources');
    api.User.get({
        action: 'current'
    }).then(function(response) {
        dispatch('SET_CURRENT_USER', response.data);
    });
};

그리고 내 안에App.vue컴포넌트:

<template>
    <a @click="readCurrentUser">read current user</a>
</template>

<script>
    import store from '../vuex/store'
    import { readCurrentUser } from '../vuex/actions'

    export default {
        replace: false,
        store: store,
        data: function () {
            return {
            };
        },
        vuex: {
            actions: {
                readCurrentUser: readCurrentUser
            }
        },
        attached: function() {
            // !!!!  HERE IS THE POINT !!!!
            // How can I trigger `readCurrentUser` action here?
        }
    }
</script>

위의 경우,<a @click="readCurrentUser">액션이 예상대로 실행되었습니다.

하지만 앱이 첨부될 때마다 액션 트리거를 켜고 싶은데, 어떻게 해야 하나요?

마침내, 나는 해결책이 매우 간단하다는 것을 알았다.

처럼vuex.actions메서드가 현재 VM 개체에 등록됩니다.

그럼, 전화:

attached: function() {
    this.readCurrentUser();
}

효과가 있습니다!

언급URL : https://stackoverflow.com/questions/37007897/explicit-call-vuex-actions-in-the-vue-component-detach-ready-function

반응형