【问题标题】:vue component ,how to update store state (vuex) via an async request(axios) in vue componentvue 组件,如何通过 vue 组件中的异步请求(axios)更新存储状态(vuex)
【发布时间】:2017-02-17 14:06:41
【问题描述】:

我正在做一个使用 vue vuex 和 webpack 的项目。我有一个 Vue 实例并导入了一个 vue 组件和一个 vuex 商店。 component 和 store 都注册到 Vue 实例。我正在使用 axios 在组件中发出异步发布请求。在得到结果后,但我无法操作商店,也无法获取 Vue 实例或组件……我该怎么办?请问?

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>

有什么方法我不需要将异步请求更改为同步请求?

非常感谢

【问题讨论】:

    标签: vue.js vue-component


    【解决方案1】:

    组件的所有方法都应该放在它的方法属性中。

    <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>
    

    【讨论】:

    • 对不起,这是方法中的拼写错误……
    • 问题是我得到响应后无法调用 mutate 函数......“this”现在变成了“window”
    猜你喜欢
    • 2018-06-14
    • 2017-01-10
    • 2018-09-05
    • 2019-06-08
    • 1970-01-01
    • 2021-09-02
    • 2020-09-10
    • 1970-01-01
    • 2018-11-10
    相关资源
    最近更新 更多