2017-06-16 51 views
2

我在Vue中有一個組件,我使用替代提交按鈕。我可以將一個處理程序傳遞給它,組件在禁用本身並將其設置爲加載狀態後調用它,並且它可以在錯誤發生後恢復(再次啓用自身),並在一切順利時顯示出漂亮的成功動畫。這種運作良好,用下面的代碼:組件中的Vue提交按鈕不提交

// Submit.vue 
<template> 
    <button :type="type" :class="classes" :disabled="loading" @click="onClick"> 
     <span class="flag" v-if="flag"></span> 
     <slot></slot> 
    </button> 
</template> 

<script> 
    import _ from 'lodash' 
    export default { 
     name: 'submit', 
     props: { 
      brand: { 
       type: String, 
       default: 'primary' 
      }, 
      // If no handler is provided, will fallback to normal submit button 
      handler: { 
       type: Function, 
       required: false 
      }, 
      flag: { 
       type: Boolean, 
       default: false 
      } 
     }, 
     data() { 
      return { 
       loading: false, 
       success: false 
      } 
     }, 
     computed: { 
      type() { 
       return typeof this.handler !== 'undefined' ? 'button' : 'submit' 
      }, 
      classes() { 
       return [ 
        `btn btn-${this.brand}`, 
        this.loading && !this.success ? 'loading' : null, 
        this.success ? 'success' : null 
       ] 
      } 
     }, 
     methods: { 
      onClick (event) { 
       if (this.success) { 
        event.preventDefault() 
        return 
       } 
       this.loading = true 
       if (typeof this.handler !== 'undefined') { 
        // Handler must return a Promise 
        this.handler.call() 
         .then(_.bind(() => { 
          this.onSuccess() 
         }, this)) 
         .catch(() => {}) 
         .then(_.bind(() => { 
          this.loading = false 
         }, this)) 
       } 
      }, 
      resetSuccess() { 
       this.success = false 
      }, 
      onSuccess() { 
       this.success = true 
       setTimeout(this.resetSuccess, 2000) 
      } 
     } 
    } 
</script> 

它回落到一個正常的,如果沒有處理程序傳遞提交按鈕,假設所有你想要的是自動禁用表單提交時的按鈕。唯一的問題是當我單擊從組件創建的按鈕時,表單未提交

我認爲這將是相當容易強制提交通過JS與onClick方法,但我想明白爲什麼它沒有。這是瀏覽器問題嗎?安全問題? Vue的問題?或者我錯過的東西可能就在我面前?

這裏有一個快速測試一個的jsfiddle:https://jsfiddle.net/03fgwgy5/ 代碼是不完全一樣,因爲我使用的是單文件組件,但要點是相同的,可以很容易地觀察到的行爲。

回答

2

在檢查是否存在handler之前,您正在將loading設置爲false。由於您將按鈕的disabled屬性綁定到loading,因此您將禁用該按鈕並阻止觸發本機點擊事件。

只需設置loading屬性,您已經檢查的處理程序後:

if (typeof this.handler !== 'undefined') { 
    this.loading = true; 
    ... 
} 

Here's a fiddle.

+0

@TomasButeler哈哈,好吧,這是實際的答案 – thanksd

+1

其中一個時間就是對的!今天早上我有一個這樣的人。 – Bert

+0

啊,很好。我有一種感覺,這是明顯的。唯一的問題是,我希望按鈕被禁用,並且不管是否有處理程序,都有'loading'類。我將最終使用JS來強制提交,但你解決了謎題:) –

1

爲了記錄在案,這裏是我落得這樣做:

onClick (event) { 
    if (this.success) { 
     event.preventDefault() 
     return 
    } 
    this.loading = true 
    if (typeof this.handler !== 'undefined') { 
     // Handler must return a Promise 
     this.handler.call() 
      .then(_.bind(() => { 
       this.onSuccess() 
      }, this)) 
      .catch(() => {}) 
      .then(_.bind(() => { 
       this.loading = false 
      }, this)) 
    } else { 
     this.$el.form.submit() 
    } 
} 

這使得我通過點擊禁用表單並顯示加載狀態,但仍然強制提交。