2017-07-21 47 views
2

我有以下的組件屬性(它基本上是一個引導報警組件):檢查道具通過驗證

props: { 
    alertType: { 
     validator: function (value) { 
      return [ "success", "info", "warning", "danger" ].indexOf(value) >= 0; 
     }, 
     default: "danger" 
    }, 
// Some more things 
computed: { 
    classes: { //Compute the correct classes for the alert type 
     var classesObj ={ 
      'alert-dismissible': this.dismissable 
     }; 
     classesObj["alert-"+this.alertType]=true; //Problem if invalid 
     return classesObj; 
    } 
} 

這種運作良好,在某種意義上說,如果我不提供警報類型,它使用「危險「,但是如果我確實提供了一個警報類型並且它沒有通過驗證,那麼alertType被設置爲該值,併發出一個控制檯警告(據我所知是預期的行爲)。

我的問題是,是否有可能在classes計算的屬性中確定alertType道具是否通過驗證(理想情況下,如果它未能獲得並使用默認值,基於組件的道具定義。

回答

1

從我能說的是,不,你不能在組件內引用道具規範,但是你可以通過在組件定義之外定義prop規範來獲得非常接近的結果,這樣你就可以使用它來設置道具和(無論出於什麼原因,prop驗證實際上似乎都不在代碼片段中運行,沒有警告是基因產生的編輯)

const alertTypeSpec = { 
 
    validator: function(value) { 
 
    return ["success", "info", "warning", "danger"].indexOf(value) >= 0; 
 
    }, 
 
    default: "danger" 
 
}; 
 

 
new Vue({ 
 
    el: '#app', 
 
    components: { 
 
    pC: { 
 
     template: '#pc-template', 
 
     props: { 
 
     alertType: alertTypeSpec 
 
     }, 
 
     computed: { 
 
     classes() { //Compute the correct classes for the alert type 
 
      const classesObj = { 
 
      'alert-dismissible': this.dismissable 
 
      }; 
 
      const alertType = alertTypeSpec.validator(this.alertType) ? this.alertType : alertTypeSpec.default; 
 

 
      classesObj["alert-" + alertType] = true; //Problem if invalid 
 
      return classesObj; 
 
     } 
 
     } 
 
    } 
 
    } 
 
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script> 
 
<div id="app"> 
 
    <p-c alert-type="success"></p-c> 
 
    <p-c alert-type="invalid"></p-c> 
 
    <p-c></p-c> 
 
</div> 
 

 
<template id="pc-template"> 
 
    <div>Alert type is {{alertType}}, classes is {{classes}}</div> 
 
</template>

+0

這幫助。順便說一下,只有當你使用Vue的開發(非微型)版本時纔會顯示警告,所以也許prop驗證只是爲了調試的目的。 – apokryfos