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 商店。 component 和 store 都注册到 Vue 实例中。我正在使用 axios 在组件中发出异步 post 请求。得到结果后,我无法操作商店,也无法获取 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>
有什么方法不需要将异步请求更改为同步请求吗?
非常感谢
组件的所有方法都应该放在它的方法中 属性。
<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>
我正在使用 vue vuex 和 webpack 开发一个项目。我有一个 Vue 实例并导入了一个 vue 组件和一个 vuex 商店。 component 和 store 都注册到 Vue 实例中。我正在使用 axios 在组件中发出异步 post 请求。得到结果后,我无法操作商店,也无法获取 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>
有什么方法不需要将异步请求更改为同步请求吗?
非常感谢
组件的所有方法都应该放在它的方法中 属性。
<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>