我在我的项目上尝试了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">
时,按预期触发了操作。
但我希望每次附加应用程序时都会触发操作触发器,我该怎么做?
答案 0 :(得分:3)
最后,我发现解决方案非常简单。
因为vuex.actions
方法将在当前vm对象上注册。
所以,请致电:
attached: function() {
this.readCurrentUser();
}
干得好!