Image de l'article 'More about props definition with Vue.js'

More about props definition with Vue.js

Declaring props with Vue.js can include more than just the definition of the data passed from the parent to the child component. Let’s see how a more complex validation is declared.

Thought I wrote on Vue props feature with TypeScript, I showcased only a simple example where the props were primitives.

But what about reference types? And what about props validation? And using TypeScript syntax in that context?

In the examples below, I use the Composition API only.

With JavaScript, it’d look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
defineProps({
  type: {
    // first you define your validation rule,
    // below, the `validValues` are represented by a string array.
    // see https://vuejs.org/guide/components/props.html#prop-validation
    validator(value) {
      const validValues = [
        "primary",
        "ghost",
        "dashed",
        "link",
        "text",
        "default",
      ];
      // if the value provided exists in the array of valid values,
      // then the prop is accepted.
      return validValues.includes(value);
    },
    // omit the following if the prop is required with no default value.
    default() {
      return "default";
    },
  },
});

With TypeScript, it’d look like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { PropType } from "vue";

defineProps({
  type: {
    // PropType is used to annotate a prop with more
    // advanced types when using runtime props declarations.
    type: String as PropType<
      "primary" | "ghost" | "dashed" | "link" | "text" | "default"
    >,
    default: "default",
    validator: (prop: string) =>
      ["primary", "ghost", "dashed", "link", "text", "default"].includes(prop),
  },
});

Credits to:

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy