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

Searching for a name in JSON or array data using jQuery can be accomplished by utilizing various methods and functions available

Having trouble searching data from an array in jQuery. When I input Wayfarer as the value for the src_keyword variable, it returns relevant data. PROBLEM The issue arises when I input Wayfarer Bag as the value for the src_keyword variable. It returns em ...

Automatically populate a div with content from a file

As I am completely new to the world of HTML, I find myself in need of quickly putting together something for work just as a proof of concept. I apologize if this question has been answered previously, but honestly, I wouldn't even know how to start se ...

Utilizing jQuery, AJAX, PHP, and MySQL for a dynamic auto-suggest feature in form inputs

Looking for ways to suggest city and state as a user types in the form input field on your website? Check out this resource that provides a solution using jQuery, PHP, and MYSQL: Solution ...

What steps can I take to troubleshoot issues when creating a React app?

While attempting to set up a react application using npx create-react-app projectreact, I encountered the following error message: PS C:\Users\ahnaa\OneDrive\Documents\Web Developent\Reaact JS> npx create-react-app project ...

Seeking a more deliberate option instead of using $(window).load, one that is not as quick as $(document)

Currently, my goal is to utilize JavaScript to conceal my preloader once the DOM and key elements have been loaded. The issue lies in the fact that various iframes on my page can significantly slow down this process. It seems that using jQuery's $(do ...

Ways to dynamically update a Vuetify 3 element's placeholder text?

Here is the code snippet from my component.vue file: <template> <v-text-field name="Foo" :label="$t('foo')" type="text" hint="This is a hint" persistent-hint >& ...

Utilize both a model and a boolean variable within expressionProperties in Formly configuration

I'm having trouble setting formly form fields to disabled based on model properties and a boolean variable. The code snippet I've tried doesn't seem to be working as expected. expressionProperties: { 'templateOptions.disabled' ...

Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instan ...

Errors are encountered when attempting to use `usePathname()` and `useRouter()` functions. `usePathname()` returns null while `useRouter()` causes errors stating "NextRouter not mounted" and "invariant

I'm encountering an issue with implementing active navlinks in NextJS version 13.4.4. I need to access the current URL for this solution, but every attempt ends up failing. My folder structure is organized as follows: .next components Header header ...

Encountering a node.js issue

Hi there, I keep encountering this error message. Can someone explain what it means? I'm not very skilled in coding, so I would appreciate any assistance :) Best regards logon fail: 65, sessionID: 6343803 events.js:85 throw er; // Unhandled & ...

invoking a JavaScript function with onClick

Every time I try deploying my code, an error is thrown saying: saveRows is not a function. Can anyone help me figure out what's going on? dataGrid.prototype = { display: function() { var self = this; var html = []; va ...

Tips for transferring a data table (an object) from a JavaScript file to Node.js

On my HTML page, there is a table displaying student names and information, along with controls to manage the table. I created a save button to save this table as an object named SIT in my JavaScript code. I was able to manually save this table in MongoDB ...

Is it possible to rearrange the positions of 2 divs using solely CSS?

I have created a unique design. On iPad, I am assigning the class 'handHeld' to the <body>, which will trigger positional changes between optionsWrapper and #container using CSS classes I've defined below on jsfiddle.net. .handHeld d ...

Transforming the timezone of a date from the Backend to the timezone selected by the user in the User

I have an API that provides dates in the format: 12/23/2023 at 03:31 a.m. CST My goal is to convert this to a date with the user-selected timezone in the following format: 12/23/2023 at 7:31 p.m. The timezone part is not required for display in the UI. c ...

Discovering indistinguishable "Feeling Fortunate" inquiries

My goal is to create a program on my website that can compare the top search results for different queries. For instance, I want it to recognize that the top search result for "twelve" and "12" is the same, leading to https://en.wikipedia.org/wiki/12_(numb ...

Guide on uploading multipart career-form data with file paths and validation in CodeIgniter with the help of AJAX

I am facing an issue while attempting to insert job form data with file uploading and validation in PHP CodeIgniter via AJAX. The code I am using is provided below, but unfortunately, it's not functioning as expected. Can anyone help me figure out how ...

React: Encountered an expression in JSX where an assignment or function call was expected

Trying to build a left-hand menu for my test application using react. Encountering a compilation error in the JSX of one of my classes. Is it because HTML elements cannot be placed within {} scripts in JSX? If so, how do I fix this? ./src/components/Left ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...

What is the best way to extract data from several SQL tables and display it in an HTML/PHP table?

In my database named result, I have two tables named res and sub. Here is an example of the contents in the res table: sno regno name sub1 sub2 sub3 sub4 sub5 1 1DU12CS100 student1 70 80 85 70 90 2 1DU12CS101 ...

Improved method for importing VueRouter dynamically for named views with the use of Promises

I'm currently facing an issue with dynamically loading my component views for Vue-Router. The import statement I'm using returns a promise instead of the actual value, even when I've tried to chain ".then" in case the promise returns another ...