我正在使用vue vuex和webpack开发一个项目。 我有一个Vue实例并导入了一个vue组件和一个vuex存储。 组件和存储都注册到Vue实例。 我正在使用axios在组件中做了一个异步发布请求。在我得到结果但是我无法操作存储而我无法获得Vue实例或组件...我怎么能用它呢? PLZ?
app.js import indexPage from './vue/index.vue' const store = new Vuex.Store(....not relavent.....) const router = new VueRouter({routes:[{path:'/', component:indexPage}]}) const app = new Vue({ el:"#app", router, store }) index.vue <template>not relavent</template> <script> export default { data(){return{}}, methods:{ dopost: function(){ axios.post('/api',{}).then(){ // apparently "this" wouldn't workhere // I've tried give this module a name and just use it // but it is just an object, not a instance. // And I couldn't use the vue instance } } } </script>有什么方法我不需要将异步请求更改为同步请求?
非常感谢
I'm working on a project using vue vuex and webpack. I've got a Vue instance and imported a vue component and a vuex store. component and store are all registered to Vue instance. I was using axios made a async post request in the component.. After I got the result but I couldn't manipulate the store and i can't get the Vue instance or component... how could i do with it? plz?
app.js import indexPage from './vue/index.vue' const store = new Vuex.Store(....not relavent.....) const router = new VueRouter({routes:[{path:'/', component:indexPage}]}) const app = new Vue({ el:"#app", router, store }) index.vue <template>not relavent</template> <script> export default { data(){return{}}, methods:{ dopost: function(){ axios.post('/api',{}).then(){ // apparently "this" wouldn't workhere // I've tried give this module a name and just use it // but it is just an object, not a instance. // And I couldn't use the vue instance } } } </script>Is there any way that i don't need to change the async request to the sync request?
Thanks a lot
最满意答案
组件的所有方法都应该放在它的methods属性中。
<script> export default { data(){ return {} }, methods: { postTo() { const self = this; // assigning this to self axios.post('/api',{}).then(){ self.$store.commit('SOME_MUTATION_TYPE') } } } } </script>All the methods of your component should go in it's methods property.
<script> export default { data(){ return {} }, methods: { postTo() { const self = this; // assigning this to self axios.post('/api',{}).then(){ self.$store.commit('SOME_MUTATION_TYPE') } } } } </script>更多推荐
发布评论