【发布时间】:2019-05-12 14:28:22
【问题描述】:
使用 Vuex 我有一个表单,当单击按钮时 (@click="loader(true)") 发送到加载程序突变以将加载更改为 true,然后将带有 Bulma CSS 的 is-loading 类设置为 true ('is-loading' : $store.state.index.loading )。
如果表单为空且带有errors.title,然后我会从服务器收到错误,这适用于输入,但如果有错误,我如何将is-loading 类设置为false?
(如果你运行它,代码 sn-p 将不起作用)
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>
【问题讨论】:
-
在这种情况下,您可能需要使用一个操作,根据服务器的响应将
state.loading的值切换为 false。 -
不要引用我的话,但应该是类似于
this.$store.commit('loader', false)的内容。 vuex.vuejs.org/guide/mutations.html -
哦。等待。我误读了。在您的
postThis方法中进行一些验证或try { } catch { }。如果您可以向我们公开该方法,可以尝试并提供进一步帮助。 -
postThis 如果使用promise,你应该对突变、状态、动作的逻辑和使用没问题。如果您有业务逻辑,则直接使用突变是不好的。我实际上会将业务逻辑放在您的操作中,然后使用提交来管理所有状态。提交(加载)然后提交(失败)或提交(完成与成功)。那么你只有一种方法可以调用。由你决定正确使用 vuex ;)
-
是的,使用 commit('loader', true) 将突变移动到操作中是有意义的,但如果您没有其他需要,那么直接使用突变并没有错,只需更改状态,这显然是例如而不是把完整的行动方法
标签: javascript vue.js vuex