Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve:

export default {
  emits: ['update:modelValue'],
  props: {
    items: {
      type: Array,
      // required: true
    },
    modelValue: {
      type: [String, Number, Boolean],
      required: true
    }
  },

  setup({modelValue, props} : any, {emit} : any ) {
    let is_active = ref(false);
    let selected = ref({
        label: props.items[0].label,
        icon: props.items[0].icon,
        class: props.items[0].class
    });

As you can see, I am using let selected to store the first object from the items array, but it doesn't seem to be working. I can display the items on my template without any issues, but facing problems in the setup. Any suggestions on how to resolve this?

By the way, the recommended practice is to use something like

let selected = reactive(props.items[0])
, but even that approach is not providing the desired outcome.

Answer №1

The issue lies in your setup() function, where you are destructuring a props property from the props argument.

           props argument
      -------------------------
setup({modelValue, props} : any, {emit} : any) {
                   ^^^^^ ❌ props.props does not exist

However, it is advised to avoid destructuring the props argument (as cautioned in the documentation) as it can lead to loss of reactivity for the prop.

To resolve this issue, refrain from destructuring the props argument. You can also enhance type inference for the props and context arguments by utilizing the defineComponent() helper function from vue when defining the component:

import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup(props, context) {
    let selected = ref({
      label: props.items[0].label,
      icon: props.items[0].icon,
      class: props.items[0].class
    });

    //...
  }
})

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

Enhance your website with a dynamic div zoom feature using the Jquery Zoom

I've been scouring the internet for a jQuery plugin that allows me to zoom in on an image. There are many options out there, but I prefer ones that display the zoomed-in image in a separate area rather than directly on the original image. For example ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...

The update function in model.findByIdAndUpdate() is failing to make changes

I am struggling to update a user model with new data using findByIdAndUpdate(). Despite my efforts, the model does not reflect the changes made. Below is the code snippet where I am attempting to use findByIdAndUpdate() to add an object: const User = ...

Protected node.js REST API

I want to ensure the security of a restful API and aim to keep it simple and stateless. What is the best way to store, generate, and authenticate API keys? I was considering using node-uuid to generate keys, storing them in Redis, and then authenticating ...

Tips for validating user input in AngularJS without using a form tag

Within a popup, I am displaying HTML content that has been copied from another div and shown in the popup. I need to validate this input field to ensure it is required, and display an error message below the input box. <!-- HTML code for changing zip c ...

Randomly positioning an image while the page is loading

I've been developing a portfolio website to showcase my design work, but I've encountered a minor issue. My goal is to have the images load in random positions and then make them draggable using Dragabilly. However, sometimes all the images end ...

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

When creating a new instance of a class, I make sure to use the

I am facing an issue when trying to call a function from ClassA within my mainClass, and vice versa. I have attempted using .bind() and .call(), but it only works when I use .bind(this) or .call(this) on functions, not when I try to instantiate a new class ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

What are the steps to execute Mike Bostock's D3 demonstrations?

I've been attempting to run Mike Bostock's See-Through Globe demonstration, but I encountered issues with the correct referencing of his json files when attempting to replicate it locally. The problem stems from this particular line of code: d3. ...

Getting the Class name in Typescript

How can you retrieve the class name from within a Class in typescript? For instance, consider this code snippet: export class SomeRandomName extends AbstractSomething<SomeType> implements OnDestroy { className = 'SomeRandomName'; Is th ...

How should one handle the potential risks presented by literal types?

As I was translating a large JavaScript project into TypeScript, something caught my attention. Consider a module that looks like this: WinConstants.ts export = { "no_win":0, "win":1, "big_win":2, "mega_win":3 } I wanted to make it truly constan ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

The Javascript navigation bar is not displaying properly on mobile devices as it should

After customizing the responsive navbar tutorial from W3Schools using CSS and JS, I encountered an issue. I wanted to include a logo and a web page title before the navbar, which worked perfectly when the webpage was maximized. However, when I resized the ...

Creating interactive and adaptable maps

Currently, I am working on making a Joomla website responsive. However, I have encountered an issue with the SobiPro Map. The problem arises when displaying a map (background img) and points (a link + img) over it with an absolute position. As a result, wh ...

Unable to display modal pop-up in ASP.NET Core MVC web application

I have developed a web application using ASP.NET CORE MVC. I encountered an unusual issue while trying to display a modal popup using JQuery. The div structure I am working with is as follows: <div class="modal fade" tabindex="-1" r ...

Vue 2 - Error: The function is not defined at HTMLInputElement.invoker (vue.esm.js?65d7:1810)TypeError: cloned[i].apply

I encountered the following error: Uncaught TypeError: cloned[i].apply is not a function at HTMLInputElement.invoker (vue.esm.js?65d7:1810) I have set up my project using vue-cli (simple webpack), and below is the code for my component: <template ...

The Angular 6 test command using npm has encountered a failure

I've been encountering a disconnect error while attempting to run Angular test cases. With over 1500 test cases written, it appears that the sheer volume may be causing this issue. Is there a way to resolve the disconnect error when running such a lar ...