Custom prop type Vue.js

Viewed 10756

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

Custom props typing in Vue2

The only solution that works for me is with @vue/composition-api.

/* eslint-disable @typescript-eslint/no-empty-interface */
import { defineComponent } from '@vue/composition-api'
import { IAddress } from '@/types'

interface Props {
    address: IAddress
    title: string
}

declare module 'vue/types/vue' {
    interface Vue extends Props {}
}

export default defineComponent({
    props: {
        address: Object,
        title: String,
    },
    setup (props: Props) {
        const address = props.address
        console.log(address)
    },
})
Related