我正在我的项目中尝试使用 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">
操作按预期触发时。
但是我希望每次附加应用程序时都触发动作,我该怎么做?