The issue of Vue.js not triggering DOM updates despite changes in data

Despite the data changing properly, the modifications are not being reflected in the DOM. Below is a simple example illustrating this issue -

<template>
  <input type="text" v-model="username" />
  <p>{{error}}</p>
  <button @click="saveData">Save</button>
</template>

<script>
  export default {
    data () {
      model.error = ''; // adding a new property
      return model; // 'model' is a global variable
    }
    methods: {
      saveData() {
        if (!this.username) {
          this.error = 'Please enter the username!';
          return;
        }
        // ... other code
      }
    }
  };
</script>

Even after calling saveData(), the error variable contains the message for an unfilled username but does not display in the paragraph.

Interestingly, there's a workaround. By updating the username property whenever the error variable changes, the updates become visible.

Answer №1

In order for Vue to access it, you must either return an error or ensure that it has proper access.

data () {
  return {
    errorMessage: '',
    dataModel: model,
  };
}

Answer №2

If the error and username properties are defined on the model for the data, you should be able to accomplish what you intend to do. Below is a simple code snippet demonstrating this functionality in action. Check out the information on Declaring Reactive Properties in the documentation for more details.

var model = {
  username: "Default"
};


new Vue({
  el: "#app",
  data: () => {
    model.error = model.error || "";
    return model;
  },
  methods: {
    updateError() {
      this.error = "Test";
    },
    updateUsername() {
      this.username = "Hello, World!";
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button type="button" @click="updateError">Update Error</button>
  <button type="button" @click="updateUsername">Update Username</button>
  <div>Error: {{error}}</div>
  <div>UserName: {{username}}</div>
</div>

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

Riot.js effortlessly generates custom tags nested within each other from various server-side files

My goal is to utilize riot.js server-side rendering in order to create a static HTML page that can be indexed by search engine spiders. I have managed to get a basic example up and running, but I am now trying to solve the challenge of dynamically loading ...

Utilizing Javascript to load and parse data retrieved from an HTTP request

Within my application, a server with a rest interface is utilized to manage all database entries. Upon user login, the objective is to load and map all user data from database models to usable models. A key distinction between the two is that database mode ...

Programmatically remove a component from the DOM in Vue 3

I am working on a project similar to a spreadsheet with draggable cells, where I can move events, which are components, around. One of the challenges I'm facing is removing a component after adding it dynamically. I have tried using this code snippet ...

Avoid interrupting the code execution until it has finished completely

Let's discuss a common scenario: $('button').on('click',function(){ // Performing AJAX requests (which may take some time); }); If the user clicks the button multiple times, numerous ajax requests can be triggered. To prev ...

Efficient Routing with React Router 4: Embracing Code Splitting and Component Remount

Here is the code snippet in question: import React from 'react' import Loadable from 'react-loadable' import { Route } from 'react-router-dom' class App extends React.Component { state = { kappa: false } ...

Using Jquery Ajax to Send Data with ASP Core ActionResult

Is there a way to successfully submit a form data using Jquery Ajax in Asp Core? AJAX CODE if (contactForm.valid() == true) { var formData = new FormData(); formData.append("Name", contactForm.find("input[name='Name']& ...

How can one adhere to Angular's recommendation of "always using dots with ngModel" while working within isolate scopes?

Currently, I am working on developing an Angular application utilizing Bootstrap. To reduce the impact of Bootstrap on my HTML code, I have implemented two directives specifically for forms: form-control.js module.directive('formControl', func ...

Creating grids and dividing them using a combination of CSS, JavaScript, and PHP

I've encountered an interesting challenge while working on a web project and would love some advice on how to tackle it: Within a database, I have a collection of images that I want to display in a grid format. The twist is that higher ranked images ...

Display or conceal a div element depending on its CSS class

I need a way to dynamically show or hide a div named "contact-form" on my website based on the CSS class of another div, which indicates whether a product is in stock or out of stock. The goal is to display the div if the class is "in-stock" and hide it i ...

Tips for preventing the caret (^) symbol from being added to a package when installing with yarn

Is there a way to prevent Yarn from adding the caret prefix to version numbers when installing packages like npm has for changing version prefix (https://docs.npmjs.com/misc/config#save-prefix)? I would like to apply this configuration only for the current ...

Updating the content of a file on an iPhone

Is there a way to update the entire document content with a response from an ajax request? I've tested out using document.body.innerHTML and document.write(), which both work on desktop Safari. However, I'm looking for a solution that will also ...

Make Angular able to open a new window using window.open instead of opening a popup

Can anyone help me figure out how to use window.open to open a PDF file in a new tab for user download? Below is the Angular 4 code I'm currently using: download() { const data = {html: this.template.toArray()[0].nativeElement.innerHTML}; th ...

Error encountered on NodeJS server

Today marks my third day of delving into the world of Angular. I've come across a section that covers making ajax calls, but I've hit a roadblock where a tutorial instructed me to run server.js. I have successfully installed both nodejs and expre ...

From Laravel Bootstrap to VUE: A Step-by-Step Guide

When I initially set up my Laravel project with Bootstrap scaffolding, I used the following command: php artisan ui bootstrap Do I need to create a completely new Laravel project in order to implement VUE scaffolding, or is it possible to convert the exi ...

React transmits an incorrect argument through the function

Having a bit of trouble passing a parameter alongside the function in my for loop to create SVG paths. The props are working fine with the correct 'i' value except for selectRegion(i) which ends up getting the final value of 'i' after t ...

I am unable to locate a declaration file for the module 'react-native-foo-package'

Whenever I try to add a new component to my pure React Native project, the screen turns completely white. The import statement for 'react-native-foo-package' has some unusual symbols next to the package name, and triggers this error message: [ ...

Is it possible to utilize context within a custom hook?

Here is a custom hook that attempts to use context inside it, but results in an error stating "Invalid hook call. Hooks can only be called inside of the body of a function component" export const useFetch = async () => { const { city, setFetchError } = ...

Using GULP and NODE, what is the best way to retrieve the Jenkins BUILD_NUMBER in JavaScript?

I am having an issue with my gulp task named getBuildNumber. This task utilizes the Child Process module to run a script. gulp.task('getBuildNumber', function() { var buildNumber = child_process.execSync("echo $BUILD_NUMBER").toString(). ...

One method successfully updates the array within the data function, while a separate method continues to find the array empty

I am facing an issue in my app where I need to update an array. The process involves fetching data from the database and adding it to the array, which works fine. However, when I try to use this updated array in another method, it seems that the array is n ...

Switch to reveal a div that holds a different HTML page

I've been struggling to create a button that opens a div containing another HTML page. Initially, the button was working but the main page was opening with the div already visible, when I needed it hidden. Now, after making some changes, the button is ...