The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening:

https://www.youtube.com/watch?v=md0FWeRhVkE

To break it down:

  • A new account can be created by a user.
  • Upon creation, the user is automatically logged in (skipping email verification).
  • Without refreshing the page, I attempt to add a category.
  • There's a custom component that is v-modeled to a data value called `category_name` (as seen in the video).
  • When I input something in the field, it should appear above the input field as I'm dumping the value there. However, this doesn't occur until after a page refresh.
  • After a page refresh, the v-model starts functioning correctly.

Can anyone shed light on why this issue arises specifically when registering a new user? It seems like the data value `category_name` isn't initialized or something until the page is refreshed?

Thank you!

Answer №1

Your personalized input file (Input.vue) needs to declare and use the value prop that v-model is connected to - refer to the documentation on how v-model works with custom components

Wouldn't this only be necessary for two-way binding? From my perspective, binding the value prop simply allows the input value to be changed from the parent component

Actually, it's not quite as straightforward. The value binding ("value from parent") is crucial every time a component is both created and reused.

Reusing existing component instances is a very common (and beneficial) optimization strategy employed by Vue. You can experiment with the example below to observe the impact of missing the value binding on a custom input.

Components are created more frequently than you might imagine. Transitioning to a "Fixed" component and then back illustrates how dysfunctional the v-model is without binding the value, especially when components are dynamically generated (e.g., in Router views or within a custom "Tab" component).

I understand this may seem like a bit of a stretch - I am unsure if this resolves the issue (sharing a git repository does not align with my understanding of a Minimal, Reproducible Example) BUT it certainly indicates a bug and I don't see anything else specifically wrong with the rest of the code...

Considering how faulty a custom input is without the value binding, it is plausible to assume that Vue developers never envisioned usage of this nature, which could lead to various "odd" and unexpected behaviors...

Vue.component('my-input-broken', {
  props: ['name', 'type', 'label'],
  methods: {
    inputHandler(e) {
      this.$emit('input', e.target.value);
    },
  },
  template: `
  <div v-if="name && type" :id="name">
        <input v-if="type !== 'textarea'" @input="inputHandler" :name="name" :type="type" />
        <textarea v-else-if="type === 'textarea'" @input="inputHandler" @blur="blurHandler($event)" :name="name" type="textarea" />
        <label v-if="label" :for="name">{{label}}</label>
    </div>
  `
})

Vue.component('my-input-fixed', {
  props: ['name', 'type', 'label', 'value'],
  methods: {
    inputHandler(e) {
      this.$emit('input', e.target.value);
    },
  },
  template: `
  <div v-if="name && type" :id="name">
        <input v-if="type !== 'textarea'" @input="inputHandler" :name="name" :type="type" :value='value' />
        <textarea v-else-if="type === 'textarea'" @input="inputHandler" @blur="blurHandler($event)" :name="name" :value='value' type="textarea" />
        <label v-if="label" :for="name">{{label}}</label>
    </div>
  `
})

const vm = new Vue({
  el: '#app',
  data: function() {
    return {
      values: [""],
      componentToUse: 'a'
    }
  },
  methods: {
    addInput() {
      this.values.unshift("")
    }
  },
  computed: {
    comp() {
      return this.componentToUse === 'a' ? "my-input-broken" : "my-input-fixed"
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>

<div id="app">
  <label for="componentToUse">Component to use:</label>
  <input type="radio" name="componentToUse" v-model="componentToUse" value="a"> Broken
  <input type="radio" name="componentToUse" v-model="componentToUse" value="b"> Fixed
  <hr>

  <button @click="addInput">Add at beginning...</button>
  <component :is="comp" v-for="(value, index) in values" :key="index" v-model="values[index]" :name="`value_${index}`" type="text" :label="`value_${index} ('${values[index]}')`"></component>
</div>

Answer №2

After some investigation, I believe I have a better grasp on the primary issue with v-model.

<input v-model="myObject[attribute]" />

Essentially translates to:

<input
  v-bind:value="myObject[attribute]"
  v-on:input="myObject[attribute] = $event"
  />

In my own experience, the challenge stemmed from the fact that the user interface wasn't updating after reassigning myObject[attribute].

To address this issue, I employed a workaround by invoking $forceUpdate() following the variable reassignment, as illustrated below:

<input
  v-bind:value="myObject[attribute]"
  v-on:input="myObject[attribute] = $event; $forceUpdate()"
  />

While I can't guarantee it will resolve your specific problem, I hope it proves beneficial to individuals encountering similar issues.

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

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

What is the best way to synchronize CouchDB with multiple PouchDB instances in an AngularJS application?

I need help with my Angular project. I'm trying to figure out how to sync multiple PouchDB databases to a single CouchDB instance without losing any data. Can anyone provide some guidance or advice? ...

What is the best way to determine the number of dimensions in a JavaScript array?

Take a look at this array and its corresponding expected output: In Javascript, is it possible to dynamically determine how many levels there are in the array ary? var ary = ["a","b",["c","d"],"e",["f","g",["h","i"],"j"]]; Output: 3 var ary = ["a","b",[" ...

Developing a webpack configuration involving two distinct setups yet utilizing identical plugins

Currently, I am tackling a project based on vue.js where I need to develop two separate SPAs - one for the admin dashboard and another for the public side. My goal is to manage these projects separately but work on them simultaneously. It would be convenie ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

ESLint: The "react" plugin encountered a conflict

In my development environment, I have a React application within a single npm component package. This React app acts as a demonstration site that consumes the component package in addition to Storybook. local-component-package ├── .storybook ├─ ...

Iterate through an array of strings within a paragraph tag

In my current situation, I am dealing with an array of strings and would like to iterate through it within a <p> tag if the array is empty. This is what I have so far: <p *ngIf="detailMessageMultilines">{{detailMessageMultilines}}< ...

New features in Next.js 13 include an updated server component and enhanced fetch capabilities for re

Is it possible to toggle the URL from the getData function? I have my main page component with JSON todos. Can I replace 'todos' with 'users' in my client component? import styles from './page.module.css' import Button from "@ ...

Tips for displaying a loading indicator above a form

I've been struggling to figure out how to display a loading indicator on top of my form without messing up the styling... My goal is to show the loading indicator when any action, like deleting an item or changing quantity, is triggered in React.js + ...

Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically. However, the Accordion feature is not functioning correctly. JSFiddle link http://jsfiddle.net/aff4vL5g/360/ Please note: I am unable to modify the HTML structure. Current table Desired output The first accordio ...

What is the best method for verifying that audio has not been loaded correctly?

After creating a script to scrape for mp3 audio file URLs and load them into my HTML audio element's src, I encountered an issue where some of the URLs were not functioning properly. As a result, the audio was unable to execute the load() method since ...

The controller element in AngularJS becomes undefined when invoked within a directive

Presented below is a snippet of my controller: myApp.controller('WizardController', function ($scope, $http) { $scope.user = { addressline1: null, cobuyer: null, validate: null, cobuyerfirstname: null, cobuyerlastname: null, ...

Arrange the items in a list in JavaScript in descending sequence

How to sort a list of records in JavaScript in descending order? var number; //dynamic number retrieved from API var test; //dynamic text retrieved from API for (var i; i <= accList.length; i++) { var odlist = 'you have :' + test + number ...

Attempting to duplicate Codepen's code onto my local machine

Trying to figure out how to make this work locally after finding it on codepen https://codepen.io/oxla/pen/awmMYY Seems like everything works except for the functionality part. I've included the JS File and the latest Jquery in my code. <head&g ...

Refreshing the dropdown selection to a specific option using AngularJS and either JavaScript or jQuery

Currently, I am facing an issue with resetting the select tag to its first option. I have implemented Materialize CSS for styling purposes. Despite my efforts, the code snippet below is not achieving the desired outcome. Here is the JavaScript within an ...

Customize Material UI (MUI) Autocomplete with preset initial selections

My goal is to develop a unique MUI Autocomplete feature that showcases a series of numbers from 1 to 50. Upon user selection, the component should initially only show numbers 1, 6, 10, 12, and 24. If the user inputs '1', it should then display al ...

How can I show/hide a div based on checkbox click on my website? It works in jsFiddle, but not on my actual site. Any suggestions?

Is there a way to show or hide a div based on a checkbox click? I've got it working in jsFiddle, but for some reason, it's not functioning properly on my website. Any thoughts on how to fix this? My goal is to offer multiple payment methods (cre ...

Guide to setting up CKeditor

I am struggling with the installation of CKEditor. After downloading the editor from the website, I inserted the code below between the head tags of my webpage: <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <script typ ...

Encountered an error while attempting to access property 'someProperty' of an undefined value in a React application

Currently, I am developing an application that involves passing variable values within a Navlink using state from one component to another. Once the values are received, they need to be loaded into input fields and then upon clicking the submit button in t ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...