首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Vue JS change submit按钮(如果错误)

Vue JS change submit按钮(如果错误)
EN

Stack Overflow用户
提问于 2018-12-11 23:00:23
回答 2查看 723关注 0票数 0

使用Vuex,我有一个表单,当按钮被点击时( loader“loader( true )”)发送给加载器,以将加载更改为true,然后设置一个带有Bulma CSS的is-loading类为true(‘is -@click=’:$store.state.index.loading )。

然后,如果表单是空的,我会收到来自服务器的错误,如果使用errors.title,这对输入很有效,但是如果有错误,我该如何将is-loading类设置为false呢?

(如果运行代码片段,它将不起作用)

代码语言:javascript
复制
export const state = () => ({
  loading: false
});

export const mutations = {
  loader(state, value) {
    state.loading = value;
  }
 }
代码语言:javascript
复制
<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>

EN

回答 2

Stack Overflow用户

发布于 2018-12-11 23:28:46

首先,不需要在全局状态(Vuex)中具有仅本地需要的状态(正在加载)。因此,典型用法如下所示:

代码语言:javascript
复制
<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>
票数 0
EN

Stack Overflow用户

发布于 2018-12-12 08:15:19

如果你像这样使用vuex。我猜你误解了vuex。因为您可以使用for局部变量,并且可以检查api结果。如果你想要分离api请求,你必须在方法中使用mapAction,在计算中使用mapGetters

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53726842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档