在 `.vue` 组件 detach/ready 函数中显式调用 vuex 动作

Explicit call vuex actions in the `.vue` component detach/ready function

我正在我的项目中尝试使用 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();
}

很好用!