使用Vuex,我有一个表单,当按钮被点击时( loader“loader( true )”)发送给加载器,以将加载更改为true,然后设置一个带有Bulma CSS的is-loading类为true(‘is -@click=’:$store.state.index.loading )。
然后,如果表单是空的,我会收到来自服务器的错误,如果使用errors.title,这对输入很有效,但是如果有错误,我该如何将is-loading类设置为false呢?
(如果运行代码片段,它将不起作用)
export const state = () => ({
loading: false
});
export const mutations = {
loader(state, value) {
state.loading = value;
}
}
<form @submit.prevent="postThis">
<div class="field">
<div class="control">
<input class="input" :class="{ 'is-danger': errors.title }" type="text" id="title" placeholder="I have this idea to..." autofocus="" v-model="newTitle">
</div>
<p class="is-size-6 help is-danger" v-if="errors.title">
{{ errors.title[0] }}
</p>
</div>
<div class="field">
<div class="control">
<button @click="loader(true)" type="submit" :class="{'is-loading' : $store.state.index.loading }">
Post
</button>
</div>
</div>
</form>
<script>
import {mapMutations,} from 'vuex';
methods: {
...mapMutations({
loader: 'index/loader'
})
}
</script>
发布于 2018-12-11 23:28:46
首先,不需要在全局状态(Vuex)中具有仅本地需要的状态(正在加载)。因此,典型用法如下所示:
<template>
<form>
<div class="field">
<div class="control">
<input
class="input" :class="{ 'is-danger': errors.title }"
type="text"
id="title"
placeholder="I have this idea to..."
autofocus=""
v-model="newTitle"
>
</div>
<p class="is-size-6 help is-danger" v-if="errors.title">
{{ errors.title[0] }}
</p>
</div>
<div class="field">
<div class="control">
<button
@click="postForm"
:class="{'is-loading': isLoading }"
>
Post
</button>
</div>
</div>
</form>
</template>
<script>
export default {
...
data () {
return {
...
newTitle: '',
isLoading: false,
response: null
}
},
methods: {
async postForm () {
try {
this.isLoading = true // first, change state to true
const { data } = await axios.post('someurl', { title: this.newTitle }) // then wait for some async call
this.response = data // save the response
} catch(err) {
// if error, process it here
} finally {
this.isLoading = false // but always change state back to false
}
}
}
}
</script>
发布于 2018-12-12 08:15:19
如果你像这样使用vuex。我猜你误解了vuex。因为您可以使用for局部变量,并且可以检查api结果。如果你想要分离api请求,你必须在方法中使用mapAction,在计算中使用mapGetters
https://stackoverflow.com/questions/53726842
复制相似问题