2017-02-18 182 views
2

我的組件的代碼是這樣的:如何在按鈕標籤中添加條件? (vue.js 2)

... 
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
    ... 
    <script> 
     import { mapGetters } from 'vuex' 
     export default{ 
      props:['idProduct'], 
      computed: { 
       ...mapGetters([ 
        'status' 
       ]) 
      }, 
      ... 
    </script> 

我想在按鈕標記添加條件。所以,當狀態=成功,該按鈕看起來是這樣的:

<button type="button" class="btn btn-default" @click="reloadProduct">Close</button> 

當狀態=失敗,該按鈕看起來是這樣的:從腳本標籤組件所

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 

狀態值(見計算)

我嘗試這樣的:

<button type="button" class="btn btn-default" {{ status == 'success' ? @click="reloadProduct" : data-dismiss="modal"}}> 
    Close 
</button> 

但是,這是行不通的

我該怎麼辦?

+0

你最好檢查單擊處理程序函數的條件。要麼繼續或關閉模態。 –

回答

1

不能綁定動態事件監聽器,

,但你可以創建另一個功能並檢測這樣的success狀態:

<button type="button" class="btn btn-default" @click="doSomething">Close</button> 

<script> 
    import { mapGetters } from 'vuex' 
    export default { 
     props:['idProduct'], 
     computed: { 
      ...mapGetters([ 
       'status' 
      ]) 
     }, 
     methods: { 
      doSomething(evt) { 
       if (this.status === "success") { 
        // Call the reloadProduct() when the status is `success`. 
        reloadProduct() 
        // Remove the `data-dismiss` attribute of the button. 
        evt.target.removeAttribute("data-dismiss") 
       } else { 
        // Add the `data-dismiss` attribute for the button. 
        evt.target.setAttribute("data-dismiss", "modal") 
        // Uncomment this if you're trying to close the modal. 
        // $('#modal').modal('hide'); 
       } 
      } 
     } 
     ... 
</script> 

編輯:好像你要關閉的引導模式,那麼您可以在doSomething()函數中取消註釋$('#modal').modal('hide');

+0

我在doSomething方法中做'console.log(this.status)',result = null。結果是成功還是失敗 –

+0

您是否已經將'status'設置爲'false'或'true'? –

+0

現在,它已經解決了。謝謝 –

0

這可能不是最好的答案,但它是一種解決方法。

if (status === success) { 
    document.getElementById("yourDivHere").innerHTML = 
    '<button type="button" class="btn btn-default" @click="reloadProduct"> 
     Close 
    </button>' 
}; 

if (status === success) { 
    document.getElementById("yourDivHere").innerHTML = 
    '<button type="button" class="btn btn-default" data-dismiss="modal"> 
     Close 
    </button>' 

更具體地說,你可以使用jQuery這樣的:

$(this).attr("your attribute", "your value"); 
+0

請注意,當您使用Vue.js時,不應該使用jQuery修改DOM。修改DOM後,Vue.js將不會重新綁定事件偵聽器。 –