Vue 3: `defineProps` allows components to locally reference declared variables

Why am I receiving a warning error message:

defineProps is referencing locally declared variables. eslint(vue/valid-define-props)

whenever I utilize a custom validator in props within an SFC <script setup> mode:

<script setup>
import { validateMarkers } from "./hooks"
import { defineProps } from 'vue'

const props = defineProps({
  markers: {
    type: [Array, Object],
    validator: validateMarkers
  }
})
</script>

This is my custom validator:

export const validateMarkers = (markers) =>
    isNotEmpty(markers)
        ? isObject(markers)
            ? markerValidator(markers)
            : isNotEmptyArray(markers)
            ? markers.every((marker) => markerValidator(marker))
            : error('Undefined type of prop marker')
        : null

What steps can I take to resolve this warning?

Answer №1

When using eslint and Vue, the warning for imported bindings has been resolved in newer versions.

If you still encounter a warning or error, here's how to address it!

To clarify, a component can have two scopes:

Setup scope:

<script setup>
// Setup scope
</script>

Module scope:

<script>
// Module scope
</script>

defineProps should not reference local variables declared in setup scope

This is because defineProps and defineEmits are hoisted out of setup into module scope

Therefore, the following code will not function correctly:

<script setup>
  const sizes = ['sm', 'md']

  const props = defineProps({
    size: {
      type: String,
      validator: val => sizes.includes(val) // <= Cannot reference `sizes`
    }
  })
</script>

How to resolve the code above?

Refer to variables that are within the module scope!

Solution 1. Imported bindings are in the local scope:
<script setup>
import { sizes } from './sizes' // <= Import it

const props = defineProps({
  size: {
    type: String,
    validator: val => sizes.includes(val) // <= Utilize it
  }
})
</script>
Solution 2. Variables declared in module scope (not script setup):
<script setup>
const props = defineProps({
  size: {
    type: String,
    validator: val => sizes.includes(val) // <= Sizes from module scope
  }
})
</script>

<script>
const sizes = ['sm', 'md'] // <= Sizes accessible in setup scope

export default {}
</script>

Answer №2

This caution is put in place to discourage this specific practice (from the eslint(vue/valid-define-props) documentation):

<script setup>
  /* ✗ BAD */
  const def = { msg: String }
  defineProps(def)
</script>

If you actually compiles without error (see the JS tab in the SFC playground).

So I believe this is a false positive that could be ignored with a comment:

<script setup>
import { validateMarkers } from "./hooks"
import { defineProps } from 'vue'

const props = defineProps({
  markers: {
    type: [Array, Object],            👇
    validator: validateMarkers, // eslint-disable-line vue/valid-define-props
  }
})
</script>

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

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Request successful but receiving no response text and content length is zero

let req = new XMLHttpRequest(); req.addEventListener('load', function (data) { console.log(data) }, false); req.open("get", "/bar.txt", true); req.send(); Feeling a bit perplexed at the moment, I can't seem to figure out what's going ...

How can I dynamically remove an option from a select dropdown if it already exists in another option using jQuery?

In order to achieve the desired functionality, I need to dynamically adjust the select options based on user input. Additionally, I want the selection to update automatically upon a change event. var dynamicCount = 1; $('#add').click(function ...

Notifying the view with a SignalR message from the controller upon event trigger

Just starting out with SignalR and attempting to set up a notification for a specific event triggered by an API. What I've attempted: Hub: public class NotificationHub : Hub { private static IHubContext hubContext = GlobalHost.Connectio ...

Encountering an error message when trying to launch an application: Module

Every time I try to launch my react-native app in git-bash, I encounter the following error message. I have already uninstalled and reinstalled node.js, cleared the cache, and attempted various solutions from Stack Overflow and GitHub with no success. ...

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

How can I utilize columns from a junction table in the "where" clause in sequelize?

Looking to execute a Sequelize query on multiple related models: SELECT Cou.country_id, cou.country_name, Sta.state_id, Sta.state_name, Dis.district_id, Dis.district_name, Cit.city_id, Cit.city_name, Loc.location_id, Loc.location_name, Sub_Loc.sub_locatio ...

Can you explain the contrast between the functions 'remove' and 'removeChild' in JavaScript?

I have recently coded an HTML page in order to gain a better understanding of how element removal functions. Code: <html> <head> <script> var childDiv = null; var parent1 = null; var parent2 = null; function ...

Tips for customizing the appearance of a redux-tooltip

After implementing the redux-tooltip from this GitHub repository, I wanted to customize its styling to better align with my application's design. However, I realized that the Tooltip-Component's divs do not have any identifiers or class names, ma ...

Symfony2 encountering difficulties in locating file after deployment

Upon launching my project on the live server, I encountered the following error: An error occurred during template compilation ("Could not locate file "@JDareClankBundle/Resources/public/js/".") in "JDareClankBundle::client.html.twig". I have tried clear ...

Does the round function always produce the most accurate floating point approximation?

Will the result of using round(3.12143345454353,2) always be equivalent to simply using the literal value 3.12? The floating point approximation would suggest so (3.12000000000000010658141036401502788066864013671875). In simpler terms, can we rely on the ...

Dominate with asyncCommand and Ajax in MVC ActionResults

I am currently diving into front-end development and working on a project that involves fixing bugs. Right now, I am utilizing Knockout/MVC ActionResults. One of my tasks is to modify a form so that it cannot be submitted with a double click. I initially ...

Validating optional fields in React

My registration form includes the following fields: Name Email Password Confirm password Optional field Select role (student, professor, secretary) Here's what I'm trying to achieve: If I want to create a user with a student role, the optional ...

Creating dependent dropdown lists is a useful way to streamline data entry and ensure accuracy in your

I am looking to create a series of 4 connected dropdown lists, structured like this: District: <select id="district"> <option>Select a District</option> <option value="district1">dstrict1</optio ...

The code to assign a value to "parentId1" using window.opener.document.getElementById is malfunctioning

Trying to retrieve the value from my child.jsp and pass it to my parent.jsp using window.opener.document.getElementById("parentId1").value = myvalue; Despite no errors appearing in the console, the value is not successfully transferring to the parent pag ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

Tips for defining the type of a parameter in a Vue Component

Is it possible to define a type 'VueComponent' for a component parameter in TypeScript? function callback(component: VueComponent???){ // some code } ...

Issue with Firefox: Click event not fired when resize:vertical is set while focusing

Issue: Firefox is not registering the first click event when a textarea has the following CSS: textarea:focus { resize: vertical; } Check out the demo: http://jsbin.com/wuxomaneba/edit?html,css,output The fix for this problem is straightforward - ju ...

Refreshing an Angular datatable using promises - reload directive

I am currently using angular-datatables along with promises and everything is working smoothly. I have various actions that can be performed on each record (using angular $http resource) such as changing a status or similar tasks. However, I find that I n ...