vue组件,如何通过vue组件中的异步请求(axios)更新存储状态(vuex)(vue component ,how to update store state (vuex) via an asyn

编程入门 行业动态 更新时间:2024-10-25 20:28:50
vue组件,如何通过vue组件中的异步请求(axios)更新存储状态(vuex)(vue component ,how to update store state (vuex) via an async request(axios) in vue component)

我正在使用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>

更多推荐

本文发布于:2023-08-05 04:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1427187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   状态   vuex   vue   axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!