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

Tips for showcasing an uploaded image with ajax

I am looking to upload an image and display it without having to reload the page. I believe this can be achieved using Ajax form submission. However, I have tried some code but the Ajax form submit function does not seem to be working for me. Can someone p ...

I am looking to present a nested array within an array in a tabular format

This is the structure of my database: [{ "firstName": "Shaun", "salary": [ { "id":1, "rate": 250, }, { "id":2, "rate": 290, } ] },{ "firstName": "Julian", "salary": [ { "id":1, "rate": 750, ...

Creating a custom math formula using a combination of Javascript and PHP

Is it possible to apply a math formula from another variable or database? var x = 7; var formula = '+'; var y = 10; By this, I mean that the variables should output = 17 (7 + 10); How can we implement this formula using Javascript or PHP? ...

How to pass a value in Vue.js?

In details-page.vue : data() { return { columns: [ { label: "task", field: "name", }, { label: "progress", field: "status", }, r ...

Using feature flags in Vue for enhanced functionality

I am interested in incorporating a "feature toggling mechanism" into my Vue application. Although I have set up a basic system, I want to explore the methods outlined in a article by Pete Hodgson. The concept of "Inversion of Decision" seems particularly i ...

Foundation 4 - image hover effect to display alternate image

I am a newcomer to Foundation 4, but I have some coding experience. Currently, I am in the process of transitioning my photography blog (www.momentaryawe.com/blog) from Wordpress with a custom theme to a custom theme built on Foundation 4. Most aspects of ...

axios encountering a 400 bad request error during the get request

I've hit a roadblock for some time now while trying to make a call to my API to fetch data using the GET method. I keep getting a 400 bad request error in Postman, even though I am able to successfully retrieve the data with a status code of 200. I ha ...

The MVC framework coupled with a robust Javascript/JQuery validation library is a winning

Currently, I am involved in a project that utilizes MVC 2.0 along with Kendo UI. Our team has made the decision to utilize AJAX validation instead of MVC Model level validation. This means that validation occurs during most "onchange" events on HTML contro ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...

After refreshing the page, the data stored in the localStorage array gets replaced

After refreshing the webpage, my localStorage array values are being overwritten. During a session, I am able to update values on the front end, and the array in localStorage gets updated accordingly. However, if multiple inputs are changed during a sessio ...

Determine the SVG arc connecting two given points

My situation involves having coordinates for points X and A, A',... as follows: X [x,y] (starting point) A [a,b], A'[a',b'], etc. (ending points) I also have information about angles XCA, XCA', etc. However, I am struggling t ...

The @Prop property decorator in Vue cannot be utilized as it is not compatible

I have a Vue 2 component with TypeScript: import Vue from 'vue'; import Component from 'vue-class-component'; import Prop from 'vue-property-decorator'; @Component({ template: require('./template.html'), }) expo ...

Click on ng-click to sort through the blog entries

Currently, I am in the process of developing a blog utilizing AngularJS and JSON. Nearly everything is functioning as expected except for one particular filter item. As I am relatively new to Angular, it presents a bit of a challenge for me. The issue ari ...

How can you retrieve the current user in express.js when incorporating socket.io?

I have a web app using the express framework and socket.io for real-time chat. I am trying to get the current user's username and create a room with them in it, but I am struggling to retrieve the user info when socket.on('connection') is ca ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

Tips on ensuring data cleanliness in jQuery input fields

Before sending the ajax request, I want to sanitize the form fields for added security. Currently, my Javascript code looks like this: jQuery(document).ready(function($) { $('#login-form').submit(function(e) { e.preventDefault(); // pr ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

Encountering issues in the terminal during the installation of React Native

When attempting to install React Native using npm install -g expo-cli, I encountered some errors. I received several deprecation warnings for various packages: [email protected]: This package has been deprecated and now only exports makeExecutableSch ...

Ways to alter the div post user authentication

I'm in the process of developing a website with a single-page application setup. I'm utilizing Node.js for the backend and Angular for the frontend. The challenge I'm facing is displaying a specific div when a user is not logged in, and swit ...