When utilizing a wrapped v-text-field, it triggers warning messages and fails to update the data properly

Recently delving into the world of vue.js, I've been experimenting with creating a form using Vue, vuetify, and vuelidate. Oddly enough, when I don't wrap the v-text-field there are no issues, but as soon as I try to encapsulate it within components, trouble arises. The value fails to update, accompanied by a warning stating "[Vue warn] Set operation on key "model" failed: target is readonly."

You can observe this issue in action on the following sandbox :

https://codesandbox.io/s/distracted-newton-dx9p4s?file=/src/components/Form.vue

To further inspect the problematic code, refer to the snippet from Form.vue below:

<script setup>
import { reactive } from "vue";
import { useVuelidate } from "@vuelidate/core";
import { required } from "@vuelidate/validators";
import StyledInput from "./StyledInput.vue";

const formData = reactive({
  username: "",
});

const rules = {
  username: { required },
};

const v$ = useVuelidate(rules, formData);
</script>

<template>
  <v-text-field
    v-model="formData.username"
    label="Username"
    @input="v$.username.$touch;"
    variant="outlined"
  ></v-text-field>
  <div>{{ formData.username }}</div>
  <StyledInput />
</template>

<style scoped>
</style>

If you're keen on exploring more variations, feel free to check out the sandbox link provided above. I'm struggling to pinpoint my error here, any insights would be greatly appreciated.

Thanks a bunch!

Answer №1

[Vue warn] Attempting to modify a prop called "model" failed: the target is read-only.

This warning is triggered by trying to change a prop value, which is happening specifically on the v-text-field component:

<v-text-field
  v-model="props.model"
  ...
></v-text-field>

Props should be considered as read-only due to the one-way data flow concept. To work around this limitation, any desired changes can be emitted to the parent component, which can then safely perform the modification on the original object. This method works well with using v-model, because the child component that receives v-model treats it as a prop and sends any changes back to the parent.

The provided codesandbox may seem complex due to the prop being two levels deep, but it is achievable. A suggestion would be to set up v-model on StyledInput:

Form.vue

<StyledInput
    v-model="formData.username2"
    label="Username 2"
    :fieldData="v$.username2"
  />

In the first child component, define the v-model prop modelValue, continue passing props to the next child, and set up the emit action:

StyledInput.vue

const props = defineProps({
  modelValue: {
    //type: String,
    required: true,
  },
})
<MyInput
  v-bind="props"
  @update:modelValue="$emit('update:modelValue', $event)"
></MyInput>

Repeat a similar process in the next child component, setting the value prop of the v-text-field and emitting changes based on the input event:

MyInput.vue

const props = defineProps({
  modelValue: {
    //type: String,
    required: true,
  },
<v-text-field
  :value="props.modelValue"
  @input="$emit('update:modelValue', $event.target.value)"
></v-text-field>

:value="props.modelValue"
represents a one-way binding. The v-text-field will display the value of props.modelValue without altering it. When a user inputs a new value, an event containing the updated value is emitted upwards all the way to Form.vue where the actual mutation takes place (using v-model). Once the new value is set, it cascades back down to be displayed again in v-text-field's :value attribute. This sequence occurs quickly, appearing seamless to the user.

View updated codesandbox here

Lastly, if passing data between multiple components becomes messy or challenging to maintain, consider utilizing a global store like Pinia for a more organized approach.

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

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

Using jQuery's .remove() function removes all of the children from the container, rather than just one at

For my latest project, I am focused on creating a seamless full-page transition using AJAX calls. The challenge I'm facing is removing content from the DOM when loading in a new page. Despite adding a unique class or ID to the element, the .remove() f ...

Using HTML and CSS to stack a DIV on top of another using z-index

I have 3 main layers on my website: 1) The main view with elements inside (#views in jsbin) - BOTTOM LAYER 2) An overlay (with a white background opacity of .8 #overlay in jsbin) - MIDDLE LAYER 3) A context menu (#contextmenu in jsbin) - TOP LAYER Wh ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...

Troubleshoot: Unable to utilize mapActions with Vuex modules

Having trouble using mapActions to reference actions in my modules. The Vuex docs say that module actions are not namespaced by default, so they should be accessible like main store actions. Here's how I have things set up: Store import * as ModuleA ...

Is there a callback or event that can be used to ensure that getComputedStyle() returns the actual width and height values?

Currently, I find myself in a situation where I need to wait for an image to load before obtaining its computed height. This information is crucial as it allows me to adjust the yellow color selector accordingly. Question: The process of setting the yello ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Changing the size of shapes in cytoscape.js when using the dagre layout

My goal is to resize the shapes of the nodes based on the size of the node text. I tried following the steps outlined in https://github.com/cytoscape/cytoscape.js/issues/649, but encountered some issues: The shapes consistently end up with equal height a ...

Having difficulty retrieving the current time of an audio element using jQuery

Currently, I am facing an issue while attempting to manage an audio element for my custom player. Despite numerous attempts, I have been unsuccessful in acquiring the currentTime and duration properties. Below is a snippet of what I've tried: var pla ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

"Despite the null date in Node.js, the validation for expiration dates less than Date.now() is still being enforced

I am currently working on implementing validation for evaluating the finish status. However, my validation is encountering a problem with the "null" value of expiresAt. It should indicate that the evaluation has been successfully completed. The issue lie ...

Using jQuery's $.ajax() function to make an asynchronous request, and then passing the

I'm currently utilizing the jQuery $.ajax() function within a parent function that passes values into the ajax call. I am looking to have a custom callback function that can access the data parameter returned from the success function of the ajax call ...

How Vue3 enables components to share props

Having recently made the switch from Vue2 to Vue3, I find myself a bit perplexed about the best approach for sharing props among multiple components. My goal is to create input components that can share common props such as "type", "name", and so on. Previ ...

Preventing Broken URLs in Jquery each

What is the best way to prevent taking images with broken URLs? jQuery.each(jQuery('img'), function(index, obj) { imageStack.add(jQuery(obj)); }); ...

Clicking on the (x) button element will eliminate the DOM node from a list

https://i.stack.imgur.com/GxVYF.png A value is being dynamically added to my page, and here is the code snippet: function favJobs(data){ number_of_jobs_applied = data.total_bookmarked; $('.bookmark-title').append(number_of_jobs_applied, " ...

The Access-Control-Allow-Origin policy does not permit requests from applications running with an origin of null, specifically for those using a file:// URL

I am in the process of creating a webpage that utilizes jQuery's AJAX feature to fetch images from both Flickr and Panoramio. While the image retrieval from Flickr is functioning properly, I encounter an issue when attempting to use $.get(url, callba ...