apokryfos
apokryfos

Reputation: 40653

Check if prop passed validation

I have the following component property (it's basically for a bootstrap alert component):

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;
     }
 }

This works well in the sense that if I don't provide an alert type it uses "danger", however if I do provide an alert type and it does not pass validation then the alertType is set to that value and a console warning is emitted (which as I understand is the intended behaviour).

My question is whether it's possible within the classes computed property to determine whether the alertType prop passed or failed validation (and ideally if it failed get and use the default value, based on the component prop definition.

Upvotes: 2

Views: 695

Answers (1)

Roy J
Roy J

Reputation: 43881

From what I can tell, no, you cannot refer to the props specification from within the component. You can get pretty close, though, by defining the prop spec outside the component definition, so that you can use it in setting up the prop and in the computed.

(For whatever reason, prop validation doesn't actually seem to run in the snippet. No warning is generated.)

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>

Upvotes: 1

Related Questions