Home

Awesome

joiprops

Use Joi Schemas for your Vue component prop validation (and deep structure defaults).

npm version Build Status Coverage Status Maintainability dependencies Status

Why?

Vue props that have deep object structure (including defaults) cannot be easily defined using standard Vue prop validation which has all-or-nothing defaults.

The Joi schema validator provides a way to do this.

How?

A Vue mixin is used as this provides sufficient access to the prop definitions before the component lifecycle starts.

Quick Example

This example creates an a prop (notice that you don't need to define this in the traditional props component attribute) that is a object with partial defaults. Using the standard Vue prop default function would obliterate the value of a.c, whereas the joiprops mixin preserves the value.

// file: Foo.vue
<template>
<div>
  <h1>Foo</h1>
  <p>A: {{ a }}</p>
</div>
</template>

<script>
import { JoiProps, Joi } from 'joiprops'

export default {
  name: '',
  mixins: [
    JoiProps({
      a: Joi.object({
        b: Joi.string().default('B'),
        c: Joi.string()
      }).default()
    })
  ],
}
</script>


// file: App.vue
<template>
<div>
  <h1>APP</h1>
  <foo :a="a"></foo>
</div>
</template>

<script>
export default {
  name: "app",
  data: function() {
    return {
      a: {
        c: 'C'
      }
    }
  },
}
</script>

// HTML:
<div>
  <h1>APP</h1>
  <div>
    <h1>Foo</h1>
    <p>A: { "c": "C", "b": "B" }</p>
  </div>
</div>

Install

npm install joiprops

Important Notes

export default {
  ...
  mixins: [
    ...
    JoiProps({...})
    ...
  ]
  ...
}

Convenience Schemas

Joi schemacs can be little verbose, so joiprops provides some convenience abbreviations:

import { JoiProps, Joi, JO, JS } from 'joiprops'

const props = JoiProps({
  foo: JO({
    bar: JS('BAR')
  })
})

// equivalent:
const props = JoiProps({
  foo: Joi.object({
    bar: Joi.string('BAR')
  })
})

The available abbreviations are:

Import the abbreviations as needed from JoiProps:

import { JoiProps, Joi, JT, JF, JB, JS, JN, JO, JA, JOu, JOd, JAd, Jr } from 'joiprops'

Building

License

Copyright (c) 2020 Richard Rodger. Licensed under MIT.