【问题标题】:Explicit call vuex actions in the `.vue` component detach/ready function`.vue` 组件分离/就绪函数中的显式调用 vuex 操作
【发布时间】:2016-08-28 17:18:03
【问题描述】:

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

在上述情况下,当我点击&lt;a @click="readCurrentUser"&gt; 时,操作按预期触发。

但我希望每次附加应用时都触发动作,我该怎么做?

【问题讨论】:

    标签: mvvm ecmascript-6 vuex vue.js


    【解决方案1】:

    最后,我发现解决方法很简单。

    因为vuex.actions 方法会被注册到当前的虚拟机对象上。

    所以,打电话:

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

    只是工作!

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 2021-07-27
      • 1970-01-01
      • 2019-11-25
      • 2017-09-09
      • 2018-09-05
      • 2016-11-22
      • 2020-04-02
      • 1970-01-01
      相关资源
      最近更新 更多