2017-07-21 45 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