Skip to content

how to access “this” in props validator

I’m working on a project using nuxt.js, I’m injecting a function in the context of the application as recommended in the official documentation

https://nuxtjs.org/guide/plugins/#inject-in-root-amp-context

but when I try to call the function inside a props validation I get an error

/plugins/check-props.js

import Vue from 'vue'

Vue.prototype.$checkProps = function(value, arr) {
  return arr.indexOf(value) !== -1
}

in a component vue

export default {
  props: {
    color: {
      type: String,
      validator: function (value, context) {
        this.$checkProps(value, ['success', 'danger'])
      }
  }
}

ERROR: Cannot read property ‘$checkProps’ of undefined

Does anyone know how I can access “this” within validation?

thanks in advance!

Answer

Props validation is done before the component is initialized, so you won’t have access to this as you are extending Vue.prototype.

Form their documentation:

Note that props are validated before a component instance is created, so instance properties (e.g. data, computed, etc) will not be available inside default or validator functions.

In general, if $checkProps is only used for checking the value of these props, I would just use a helper function.

// array.helpers.js
export function containsValue(arr, val) {
  return arr.indexOf(value) !== -1
}

// component
import { containsValue } from 'path/to/helpers/array.helpers';
props: {
    foo: {
       //
       validator(value) {
          return containsValue(['foo', 'bar'], value);
       }
    }
}

Update

Based on your comments, if you don’t want to import this specific function over and over again, you can just Array.prototype.includes see docs

// component
props: {
    color: {
       //
       validator(value) {
          return ['success', 'danger'].includes(value);
       }
    }
}