Exploring Vue3's defineprops feature in conjunction with v-model within a child component

It seems that directly changing the props value in a child component is not recommended, but I have discovered a way to do it successfully. I am curious about the reasoning behind this behavior.

Just for context: I am working with vue3+vite

For instance:

<template>
    <input v-model="price"/>
</template>

<script lang="ts" setup>

defineProps({
    price : Number
});

</script>

This code snippet can modify the props value based on user input without any warnings or errors.

On the other hand, if I write it like this:

<template>
    <input v-model="props.price"/>
</template>

<script lang="ts" setup>

const props = defineProps({
    price : Number
});

</script>

A warning will appear in the console when trying to change the prop value directly.

I want to point out that no computed property was implemented to handle the prop change.

Is this considered a bad practice?

Answer №1

It is advisable for both components to issue a warning when changes occur. This is important because the parent component may not always be aware of any modifications unless they are explicitly made within it. Allowing the parent component to validate these changes ensures that only the designated owner can make alterations to the data.

Instead of directly mutating the data, emitting an event is recommended. The following code snippet demonstrates the conventional way of implementing this approach:

 <input :value="price" @input='$emit("input", $event)'/>
// or
 <input :value="price" @update:value='$emit("update:value", $event)'/>
// or
 <input :value="price" @input='$emit("update:value", $event)'/>

In Vue, both the props object and its properties are automatically exposed in the template, allowing easy access to them.

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

Having trouble getting the form to submit using AJAX

=====ANOTHER UPDATE==== (if anyone is interested!) The previous solution I shared suddenly stopped working for some reason. I added a beforeSend function to my ajax request and inserted the section of my JavaScript code that validates my form into it. It&a ...

Encountering a problem with the persistent JavaScript script

I have implemented a plugin/code from on my website: Upon visiting my website and scrolling down, you will notice that the right hand sidebar also scrolls seamlessly. However, when at the top of the screen, clicking on any links becomes impossible unless ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

Several examples of objects utilizing the identical function as the most recent instance

While working on a new feature for a Javascript library, I ran into an interesting issue. It seems that when a function of an object utilizes a closure and a promise together, all instances of the object end up using the most recently created version. This ...

Problem with Bootstrap multiselect: it only opens the first time, and stops working after an ajax call

I am having trouble using Bootstrap multiselect with jQuery ajax. When I run the ajax code, the multiselect button stops working properly. To see the issue in action, click here: and look at the last multiselect dropdown. Here is the ajax code snippet: ...

What is causing my app.css to be reluctant in displaying the outcome?

Having an HTML page called chat.blade.php and a CSS file named app.css, I am facing an issue where the CSS changes are not reflecting on the page after running the PHP dev command. It might be possible that I have incorrectly written the path in the HTML f ...

Creating a Three.js 3D Text Effect with Layers of Letters

Why are my 3D text letters overlapping in the threejs TextGeometry when viewed from an angle? https://i.sstatic.net/W0ocu.png See the code snippet below: class MyScene { // Code for handling Three.js scene and elements constructor(elementSelector ...

How can values be populated from an input box in the background in Vue.js?

I'm working on a project that involves Vue.js and Quasar. One of the requirements is an input field initialized with 10 zeros, only allowing numeric numbers. The catch is that when adding a number, it should fill in from behind. "0000000000" -> a ...

Retrieve the chosen element from a jstree

How can I retrieve the selected Node from a jstree? This snippet shows the code in the View section: <div id="divtree" > <ul id="tree" > @foreach (var m in Model.presidentList) { <li class="jstree-clicked ...

What could be causing Django REST Framework to block non-GET requests with a 403 Forbidden error from all devices except for mine?

Currently in the process of developing a web app using a Django REST Framework API. It runs smoothly on the computer where it was created (hosted online, not locally), but when trying to access the website from another computer, all GET requests work fine ...

Searching for array keys in JavaScript/jQuery can be done with the indexOf method

I am facing an issue with searching through an array named members. Each element in this array consists of a name as the index (e.g. "John Smith") and an array with "degree" and "id". Here is an example structure: https://i.sstatic.net/bDI2Y.png My searc ...

Troubleshooting Angular 2 ng-if issues

Is there a way to dynamically apply CSS styles to an element that has an ng-if condition, even if the condition fails? It currently works fine when the condition is true, but I'm looking for a solution that allows me to modify the element regardless o ...

Transferring data from a form to a function in JavaScript

Hey there! I've been working on a form that sends a value to a new window, but for some reason, the value val2 is showing up as null in the new window instead of being passed. Here's my code: function sendValue(value) { ViewImg = window.ope ...

Position text above an image using CSS

.content { float: left; width: 33.33%; font-weight: bold; text-align: center; margin-top: 5px; margin-bottom: 2px; overflow-wrap: break-word; } .content_div { position: absolute; width: 100%; left: 0; top: 100%; font-size: 16px } ...

Revolutionizing user experience: New feature seamlessly triggers button actions with the power of "enter"

I need assistance with modifying a form that contains two buttons and several text inputs. Currently, if the enter key is pressed, it triggers a click event on the first button. However, I want to modify this behavior so that if any of the text boxes are f ...

javascript The onclick function works only for a single interaction

Every time I click on the Button, the first click triggers func1 successfully. However, subsequent clicks fail to execute the function. Even the alert('func1') statement is not being displayed. What mistake am I making here? func ...

Warning: The React Router v6's Route component is unable to find the origin of the key props

I recently came across an error in my console and I'm unsure which list is causing it. Is there a way for me to trace back the origin of this error so I can pinpoint where to fix it? The error seems to be related to the React Router component, which ...

Tips for sending a tab id to a URL using jQuery

Upon examining the code snippet below, it is apparent that I am attempting to pass the value of a tab's id to a URL. In this instance, I am displaying it in HTML just for illustrative purposes; however, the hashtag id fails to be transferred to the UR ...

nggrid encountered an error due to an unknown provider: GridServiceProvider, which is linked to GridService and HomeController

I followed the ng-grid tutorial found at After completing all the steps, I encountered the following error in the console: Error: [$injector:unpr] Unknown provider: gridServiceProvider <- gridService <- homeController http://errors.angularjs.org/1 ...