Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom prop type Vue.js

Is there a way to create custom prop types (and extend it with validation) for Vue.js props?

In the below example you'll find the Object prop background. Instead of an Object, I would like to have a custom prop type Image. Image would check if src and alt are filled, rest would be optional.

What we have now:

export default {
  props: {
    background: {
      type: Object,
      src: String,
      srcset: String,
      alt: String,
      title: String,
    },
  },
};

What I'd like to have:

class customPropImage {
  // magic ...
}

export default {
  props: {
    background: Image,
  },
};
like image 562
Warre Buysse Avatar asked Nov 01 '18 05:11

Warre Buysse


1 Answers

Sure you can do it. According to the Vue documentation you can set the type to the constructor of your custom type. With custom validation it could look something like this:

function CustomImage () {
  // Magic
}

Vue.component('blog-post', {
  props: {
    myImage: {
      type: CustomImage,
      validator: function (value) {
        return true; // or false based on value of myImage
      }
    }
  }
})

Here is an example on codesandbox

like image 131
Devin Crossman Avatar answered Sep 22 '22 13:09

Devin Crossman