Vue 3: The correct way to properly update component props value with the composition api

I have a component similar to this one:

<template>
  <div>
    <p>Current coordinates: <strong>{{ coords }}</strong></p>
    <button type="button" @click="updateCoords">
  </div>
</template>
<script>
export default {
  props: {
    coords: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    const updateCoords = () => {
      props.coords = [38.561785, -121.449756]
      // props.coords.value = [38.561785, -121.449756]
    }
    return { updateCoords }
  },
}
</script>

I attempted to update the prop coords value using the updateCoords method but encountered an error message:

Uncaught TypeError: Cannot set properties of undefined (setting 'coords')

How can I correctly update the prop value in my situation?

Answer №1

Props in Vue.js components are read-only by default:
Learn more about one-way data flow

If you need two-way binding for props, you can implement the v-model pattern:
Understand the 3.x syntax changes

<template>
  <div>
    <p>Current coordinates: <strong>{{ coords }}</strong></p>
    <button type="button" @click="updateCoords">Update Coordinates</button>
  </div>
</template>
<script>
export default {
  props: {
    modelValue: {
      type: Array,
      required: true
    }
  },
  emits: ['update:modelValue'],
  setup(props, {emit}) {
    const updateCoords = () => {
        emit('update:modelValue', [38.561785, -121.449756])
    }
    return { updateCoords }
  },
}
</script>

Answer №2

If you need to update the props and make changes in vue 3, your code should be structured as follows:

<template>
  <div>
    <p>Current coords: <strong>{{ coords }}</strong></p>
    <button type="button" @click="updateCoords">
  </div>
</template>
<script>
export default {
  props: {
    componentPropsName: {
      type: Array,
      required: true
    }
  },
  emits: ['update:componentPropsName'],
  setup(props, {emit}) {
    const updateCoords = () => {
      emit('update:componentPropsName', [38.561785, -121.449756])
    }
    return {updateCoords}
  },
}
</script>

However, the key aspect is to define your prop in a parent component like this:

//parent component 
<child-component v-model:component-props-name="value"/>

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

The express.js GET method is unable to retrieve the value of req.body

I have experience working with Vue3, Vuex, Express.js, and MySQL. In the code snippet below, when I use the router get method, I noticed that calling "console.log(req.body)" displays "[object Object]", and calling "console.log(req.body.userid)" shows "unde ...

Add a variety of parameters to the URL in order to make an AJAX request

I want to dynamically add values from checked checkboxes to a URL for use in an AJAX call. I only want these values to be added to the URL if the checkbox is checked. If a user checks and then unchecks, I do not want that value included in the URL. Below ...

The $.ajax method seems to be experiencing some issues, but fortunately, the $.getJSON

I'm in the process of retrieving the share count for Pinterest and the following code is functioning effectively: var pi_like_count = 0; PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=? ...

django leaflet - dynamically adjusting controls on HTML page with the click of a button

Presently, I am utilizing django-leaflet along with leaflet-draw controls. My goal is to make the draw controls accessible (and add them to the map) based on a specific event, such as toggling a button. Below is a basic jQuery structure that I currently h ...

You cannot pair Reanimated 2 withSequence using a direct value

Trying to implement withSequence with a direct value as the initial input resulted in crashing the application. animatedValue.value = withSequence(startValue, withTiming(endValue)); Although the following code appeared to be functioning correctly, it did ...

Is object rest/spread properties not supported by Node.js version 6.3.1?

After attempting to run this code in Node.js v6.3.1 CLI, the following output was generated: let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; console.log(x); // 1 console.log(y); // 2 console.log(z); // { a: 3, b: 4 } Unexpectedly, the output was diffe ...

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

Accessing the URL causes malfunctioning of the dynamic routing in Angular 2

I am currently working on implementing dynamic routing functionality in my Angular application. So far, I have successfully achieved the following functionalities: Addition of routing to an existing angular component based on user input Removal of routin ...

I attempted to upload an image using the Google Drive API, but encountered an error in the response

I am attempting to upload an image using the Google Drive API, but I encountered an error in the response message. The error reads as follows: "Failed to load resource: the server responded with a status of 403 ()" ...

What is the most effective method for organizing and retrieving information on numerous topics?

Recently, I have been working on a simple chat bot project using JavaScript for the purpose of practice and enjoyment. My intention is to build upon this project and optimize it as I progress. One issue I have encountered is the inefficiency of the search ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

sending information to PHP through AJAX dynamically

I implemented a registration form that utilizes function user_reg(user_name,user_email,user_pswd) { var serverpath=window.location; alert(serverpath); var dataString = 'name='+ user_name + '&email=' + user_email + '&psw ...

Simple code for form with email confirmation

I'm looking to create a simple form for my website that sends an email notification. The current code I have doesn't automatically send the email notification. Can anyone help me with adding this feature? <!DOCTYPE html> <html> <b ...

Creating a Step-by-Step Sequential Slider

How can I create a slider with 3 specific positions - 0, 50, and 100, while also implementing restrictions that prompt a confirmation message for each position? <input type='range'> ...

What is the process for sending text messages in a local dialect using node.js?

Having an issue with sending bulk SMS using the textlocal.in API. Whenever I try to type a message in a regional language, it displays an error: {"errors":[{"code":204,"message":"Invalid message content"}],"status":"failure"} Is there a workaround for se ...

Unable to retrieve scroll position utilizing 'window.scrollY' or 'window.pageYOffset'

Issue I am facing a problem where I need to determine the scroll position in order to adjust the tooltip position based on it. This is how my tooltip currently appears: However, when I scroll down, I want the tooltip to toggle downwards instead of its c ...

Next JS Dynamic Routing displays successful message on invalid routes

I have been using the App Router feature in Next JS along with Strapi as my CMS. When I make a query to the API endpoint in Postman, I receive the expected results. Requests for routes without corresponding slugs return a 404 error, while only routes with ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...