Vue component failing to re-render after data modification

I'm a Vue beginner and I am attempting to showcase a list of "notes" that should update once a button is clicked (I have manually set the value to add for now). However, after adding a new item to the array, the changes are not reflected on the user interface. I am using Vue3, and the unique :key attribute is correctly implemented. My other "widgets" that retrieved data from an API response worked fine, so I wonder if this issue is related to handling asynchronous responses when dealing with APIs compared to simply appending/pushing to the data array?

<template>
 <Widget class="notes" :style="style" @load="showNotes()">
<h3>Notes</h3>
<p v-for="item in data" :key="item.id">{{ item.note }}</p>

<button @click="addNote()">Add</button>
</Widget>
</template>

<script>
import Widget from "./Widget.vue";;

export default {
  name: "Notes",
  props: {
    widgetWidth: Number,
  },
  computed: {
    style() {
      return "max-width: " + this.widgetWidth + "px";
    },
  },
  data() {
    return {
      notes: undefined,
    };
  },

  methods: {
    addNote() {
      var x;
      if (!this.data) {
        this.data = [];
        x = 0;
      } else {
        x = this.data.length;
        console.log(x);
      }
      this.data.push({ id: x, note: "another" });
      console.log(this.data);
    },
    showNotes() {
      this.data = [{ id: 0, note: "init" }];
    },
  },
  beforeMount() {
    this.showNotes();
  },
  components: { Widget },
};
</script>

<style scoped>
.notes {
  min-width: 100px;
  word-wrap: break-word;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.notes > * {
  flex-grow: 1;
}
</style>

Answer №1

The reason for that issue is due to your manipulation of the data property when it should actually be the notes property. Additionally, you can initialize the notes property without using the @load event or beforeMount event.

Check out this working example

Answer №2

Implement a computed property named "notes" that retrieves the contents of the notes property from your data object. Utilize the v-for directive to iterate through each item in the notes array. Upon clicking the button, the notes within your data object will be refreshed. The computed property is designed to detect this change and efficiently update the user interface.

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

Incorporate a loader when making an AJAX request and then conceal it after it has successfully completed

I find myself a bit puzzled here. Currently, I'm developing a JavaScript form that sends values to a PHP page (submit.php). If the PHP page returns a success message, I plan to redirect the user to another page (success.php). var url = 'submit. ...

Using Geolocation in HTML5 and JavaScript

Currently, I am working on my debut mobile web application and have successfully integrated Google Maps into it using Geolocation JavaScript API version 3. Now, I am looking to add a button that, when clicked by the user, centers the map on my location o ...

Link that causes the regular expression test to hang

My goal is to create a regular expression that can accurately identify URLs. I found the code snippet for this on Check if a Javascript string is a url. The code looks like this: function ValidURL(str) { var pattern = new RegExp('^(https?:\/&b ...

Is there a way to set up HTML5 Video.js in Boonex Dolphin?

My current project involves utilizing the Video.js Source Code to update the video player on my website that currently uses Boonex Dolphin. I am looking to transition from the flash player used by Dolphin to HTML5. Dolphin's modules contain specific f ...

TypeError: The function cannot be performed on the value of 0 in the Array.from

I encountered a peculiar error while attempting to utilize Array.from with Array.prototype.map. let fn = Array.from.bind(Array); // [Function: bound from] fn('test') // [ 't', 'e', 's', 't' ] ['test ...

The URL may change, but Angular remains on the same page without navigating

I am encountering an issue with 2 links in my application. The first time I click on any one of them, it navigates to the corresponding page without any problem. However, when I click on the second link after that, the URL changes but the navigation does n ...

"Angular encountering an error with converting a string to a date due to

I have a date stored as a string in the format '2022-07-15T09:29:24.958922Z[GMT]'. When I try to convert it to a date object, I am getting an error saying it is an invalid date. Can anyone help me with this issue? const myDate = response; / ...

Issue with importing global Vue object in Vue.js 3

Trying to make sense of the Vue 3 CLI output has been driving me crazy, especially when it comes to integrating it with different tutorials and plugins that all rely on the Vue object, such as Vue.createApp(.... In my project, I can use import {createApp} ...

Prevent automatic refreshing of React app on remote devices

My friend and I are collaborating on the development and testing of a React app simultaneously. He accesses the app from my machine using my IP address but encounters an issue where every time I save something in the code, the app reloads on both of our ...

Use PHP to redirect a webpage as an alternative to utilizing JavaScript

Recently, I encountered an issue where I created a form on inde1.php and utilized JavaScript to post data to login.php. My current goal is to redirect the user to another page once login.php has been successfully executed. Below is the JavaScript code on ...

Interaction between an Android app and a web page

Looking to develop a mobile app capable of sending messages and images to a webpage. Seeking guidance on how to bring this vision to life. Any assistance would be greatly appreciated in achieving this project. ...

Can anyone explain how to pass a toggle state along with its onChange function in Ionic React?

Imagine I have this toggle element: <IonToggle id="IonToggleDarkMode" slot="end" checked={vars.darkMode} onChange={darkModeToggle}></IonToggle> The value of vars.darkMode represents the current state of the toggle, which is ...

Designing access to data in JavaScript

As I work on developing my single page app, I find myself diving into the data access layer for the client-side. In this process, a question arises regarding the optimal design approach. While I am aware that JavaScript is callback-centric, I can't he ...

What are the steps to implementing imgix-js via command line?

$(document).ready(function () { var imgixOptions = { updateOnResizeDown : true, updateOnPinchZoom : true, fitImgTagToContainerWidth: true, fitImgTagToContainerHeight: true, autoInsertCSSBestPractices: true, ...

What is the process for integrating Bootstrap v5 (js + css) into a Nuxt.js v2.14 project with Vue v3?

Currently, bootstrap-vue does not have compatibility with both vue v3 and bootstrap v5. I am seeking guidance on how to directly import bootstrap files into my nuxt v2.14 project. Can someone provide me with a specific example of how to achieve this? Sin ...

Validating uploaded files in Vue and Laravel: A guide for frontend file validation

I am currently working on a Vue app that has an image uploader feature allowing users to upload multiple files. I want to implement validation to ensure that only images of a specific size are uploaded. If the uploaded files do not meet the requirements, I ...

JSON has encountered an unconventional string at position 41 that was not anticipated

Attempting to learn Javascript as a beginner, I am facing an error that is puzzling me: SyntaxError: /home/runner/myrepl/config.json: Unexpected string in JSON at position 41 Upon checking my index.js file, it seems correct at position 41 (at least I beli ...

Issues in the d3.js chart

I'm facing an issue with some incorrect lines appearing in my d3.js chart. Strangely, the problem seems to disappear when I switch tabs on Chrome and return to the chart's tab. It's puzzling to figure out the root cause of this issue, so I ...

VueJS avoids displaying a specific data in every iteration of a v-for loop

Presented below is the code that I have managed to successfully get working: <span v-for="(item, index) in storedUserItems"> <template v-if="item.strength"> <img @mouseover="itemInfo(item, index)" style="padding: 5px;b ...

A guide on displaying a JSON object using the ng-repeat directive

Looking to create a dynamic treeview menu with angularJS? Wondering how to achieve the desired results using a controller ($scope.results) and JSON data? Check out the code snippet below for an example of how to structure your treeview: <ul> < ...