`.vue`组件分离/就绪函数中的显式调用vuex动作

时间:2016-05-03 15:11:18

标签: mvvm ecmascript-6 vuex vue.js

我在我的项目上尝试了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">时,按预期触发了操作。

但我希望每次附加应用程序时都会触发操作触发器,我该怎么做?

1 个答案:

答案 0 :(得分:3)

最后,我发现解决方案非常简单。

因为vuex.actions方法将在当前vm对象上注册。

所以,请致电:

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

干得好!