Exploring the way to reference 'this' within props validation

Currently, I am engaged in a project using nuxt.js where I am implementing a function into the application context as advised by the official documentation.

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

However, I encountered an issue when trying to invoke the function within a props validation process.

/plugins/check-props.js

import Vue from 'vue'

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

This is happening within a Vue component:

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

ERROR: Cannot read property '$checkProps' of undefined

I am seeking guidance on how to access "this" within the validation process.

Your help will be much appreciated. Thank you!

Answer №1

Validation of props occurs prior to the initialization of the component, which means that accessing this while extending Vue.prototype is not possible.

According to their official documentation:

Keep in mind that props are checked before a component instance is generated, so properties like data and computed will not be accessible within default or validator functions.

If you only need to verify the values of these props using $checkProps, it might be more efficient to utilize a helper function instead.

// 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

In response to your feedback, if you wish to avoid importing the same function repeatedly, consider utilizing Array.prototype.includes as an alternative. You can consult the documentation for more information.

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

Answer №2

According to the information provided on the documentation:

Prior to the creation of a component instance, props undergo validation which means that instance properties such as data, computed, etc will not be accessible within default or validator functions.

Answer №3

To gain access to the nuxt plugins, you can utilize the window object. This is my method for accessing the i18n library:


{
   validator: (value: any): boolean => {
      return window.$nuxt.$te(value);
   }
}

In your specific scenario:


{
   validator: (value: any): boolean => {
      return window.$nuxt.$checkProps(value, ['success', 'danger']);
   }
}

It's essential not to prototype in the window object. Instead, let the nuxt manage it with a plugin:

Path: plugins/check-props.js or .ts


function checkProps(value: any, arr: string[]): boolean {
  return arr.indexOf(value) !== -1
}

const $checkProps: Plugin = (_context: Context, inject: Inject) => {
  inject('checkProps', checkProps);
};

export default $checkProps;

Then, include it in the nuxt config:


{
  plugins: [{ src: 'plugins/check-props.js', ssr: true }]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you in the business of building JavaScript hubs?

I have a unique setup where my express server is in charge of handling all routing and session functionalities. I've envisioned a system where logged-in users can connect to distinct "hubs" based on the location of each hub. My idea was to treat each ...

What is the process of generating a dynamic card/button element on an ASP.net webpage using information from the backend database?

I'm faced with a challenge of displaying employees' names and titles from a MSSQL Server database table on an ASP .NET webform as individual "card" objects. Currently, I am able to showcase a static number of records by using an asp button object ...

Exploring the depths of a nested object to locate the value of a specific key: a step-by-step guide

I have a JavaScript object structured like this. My goal is to loop through the object and extract the values for the Hostnames const data = { "error1": { "7": [ { "ErrorType": "Error-1A", ...

Can debugging AngularJS in MVC be done in Visual Studio 2013 Ultimate?

Annoyance: When working on my application, I often encounter bugs that require debugging. I find myself opening Chrome, then Dev Tools, and using its less than ideal debug tools to troubleshoot the issue. Desire: It would be fantastic if I could simply se ...

Even though I have the image button's ID, I am unable to successfully click on it

I am facing an issue where I can't seem to click on an image button even though I know its ID: driver.findElement(By.id("its Id")).click() Unfortunately, I cannot provide the website link as it is not a public website. However, I have pasted the HTM ...

Is it possible to target only those divs within a class that wrap to a new line?

I currently have a series of 7 to 12 divs with the same styling, all floated to the left. Is there a CSS selector that can target the ones flowing onto a second row? I doubt this is achievable with standard CSS, so I'm curious if anyone has any jQuery ...

JavaScript does not function properly on dynamically loaded content from AJAX requests and it is not relying on

I am currently using ajax to load all content from 'mysite/math/' into math.php. I want to render the loaded math content using katex. KaTeX GitHub Inside math.php, I include the Katex library from the CDN mentioned in the link above. The HTML ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...

Whenever I attempt to include state in a React class that is declared as a constant, I consistently encounter the error message: "TypeError:

Apologies for the redundancy, but as a newcomer to React, I previously inquired about a similar issue and have since modified my code. My current challenge involves trying to access a state value within a const React class. Below is the excerpt from my Ar ...

Tips for creating a Discord bot that can respond to inquiries with varying responses

Lately, I've been working on a Discord bot that selects a random response from an array of replies. My goal is for it to display an error message if the question is unknown or if no arguments are provided after the command. I currently have some code ...

Button in Bootstrap input group moves down when jQuery validation is activated

Check out my bootstrap styled form: <div class="form-group"> <label for="formEmail">User Email</label> <div class="input-group"> <select class="form-control" data-rule-emailRequired="true" ...

I'm unsure about the JavaScript toolkit framework's handling of selecting HTML class attributes

I have been exploring the Electron Framework using a JavaScript toolkit known as Xel. In my main.js file, I am working with the following syntax: document.querySelector("menu.selected").className.remove('selected') In my Xel code snippet, I hav ...

Switch back and forth between adding and removing a table row using jQuery

Currently, I am developing a drop-down feature for a table that populates its data using MySQL. The functionality involves creating a new table row below the current one when a user clicks a button. However, instead of generating multiple new rows each tim ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

Creating files with Node.js is a straightforward process that can be achieved with

Consider this JSON structure: { "extends": "core-range", "dependencies": [ "paper-progress", "paper-input" ], "jsdoc": [ { "description": "Triggered when the slider's value changes.", "kind": "event", "name": "co ...

Setting up laravel-mix to seamlessly work with @material components in vue.js

I need assistance with configuring material-web-components to function properly with vue.js components. The issue arises when trying to import a @material component scss into my vue component. Here is an example of the code in SomeVueComponent.js: <st ...

Script tag in NextJS

After numerous attempts, I am still struggling with a specific task on this website. The challenge is to insert a script tag that will embed a contact form and newsletter sign-up form, among others, on specific pages of the site. For instance, the contact ...

The dropdown value is limited to storing data up to the specified space

I am facing an issue with storing data selected from the second dropdown in my form. The first dropdown is for selecting the Brand Name of a car, and the second dropdown retrieves data from the database based on the brand name selected. I have used a div t ...

Tips for managing the onblur event using selenium automation framework

I want to trigger an onblur event when I click away using JavaScript. I tried the following code: ((JavascriptExecutor)getDriverProvider().executeScript("document.getElementByXpath('xpath here').onblur();"); However, it doesn't seem to wo ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...