vue.js data fails to update after clearing

Incorporated within my page is a vue.js item that monitors modifications made to a form. The code for this functionality is as follows:

var changes_applied = [];

var changes_applied_block = new Vue({
    name: "ChangesApplied",
    el: '#changes-applied',
    data: {
        items: changes_applied
    },
    methods: {
        remove: function(index) {
            changes_applied.splice(index, 1);
        }
    }
});

Whenever a change is detected, it gets added to the changes_applied array and displays in the "Changes Applied" section as expected. The removal process also functions correctly by invoking the remove method on the vue object.

In addition, there's a separate "clear" button that does not relate to the vue instance. Upon clicking this button, the data source is reset to an empty array using changes_applied = [];

The issue arises after clearing the data with the button. Subsequent modifications or additions to the changes array no longer reflect in the vue component—almost like the vue element is no longer linked to the changes_applied array.

Should there be additional bindings or steps required for proper synchronization, or is there a prescribed "vue way" to reset the vue data without direct manipulation of the source array?

Answer №1

It's important to note that Vue doesn't react effectively to changes made directly on the changes_applied array. The best practice is to avoid manipulating changes_applied and instead focus on modifying this.items directly. When you reassign the reference of this.items, it can break functionality because Vue no longer recognizes it as the same array.

To properly remove items, utilize a method like this:

methods: {
    remove: function(index) {
        this.items.splice(index, 1);
    }

If you need to reset the array, simply use:

this.items = []

By following these guidelines, your code will behave as expected within the Vue framework.

Answer №2

When you initialize the items array with changes_applied, it is just the default value for items when the instance is created and does not maintain bindings. Therefore, changing the changes_applied will not affect the items array on the vue instance.

For example:

new Vue({
  el: '#app',
  data: function () {
    return {
      items: myArr,
      newItem: ''
    }
  },
  methods: {
    addItem () {
      this.items.push(this.newItem)
      this.newItem = ''
    },
    remove (index) {
      this.items.splice(index, 1)
    },
    clear () {
      this.items = []
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <input type="text" v-model="newItem" /> 
  <button @click="addItem">Add</button> 
  <button @click="clear">Clear</button>
  <p v-for="(item, index) in items" @click="remove(index)">{{item}}</p>
</div>
<!-- from outside vue instance-->
<button onClick="clearFromOutside()">clear from outside</button>
<script>
var myArr = ['hola', 'mundo'];
  function clearFromOutside() {
    console.log(myArr)
    myArr = [];
    console.log(myArr)
  }
</script>

Answer №3

Mark_M has already provided a detailed explanation, so I will showcase a demo to make it easier to grasp the concept.

Instead of directly manipulating the array values, you can copy them to a separate data variable and perform all operations on that data:

const changes_applied = [
  {id: 1},
  {id: 2},
  {id: 3}
];

const vm = new Vue({
  el: '#app',
  data: {items: changes_applied},
  methods: {
    add() {
      const id = this.items.length + 1
      this.items.push({id})
    },
    remove() {
      this.items.pop()
    },
    clear() {
      this.items = []
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <div>
    <button type="button" @click="add">Add</button>
    <button type="button" @click="remove">Remove</button>
    <button type="button" @click="clear">Clear</button>
  </div>
  <ul name="list">
    <li v-for="item in items" :key="item.id">
      Item {{ item.id }}
    </li>
  </ul>
</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

Steps for adding data to an object property within a mongodb document:

I need to make a request to a mongodb database, specifically for updating an object. Here is an example of the object: { id:"1", requestType : { "api1" : {count:12,firstTime:12}, "api2" : {count:6,firstTime:18} } } After retrieving the d ...

What is the best way to transfer Javascript variables from an HTML template to a view function in Django?

Currently, I am developing a website using Django. One of the features I'm working on is a form in my HTML page that includes a textbox for users to input their name with a label "Enter your name". Underneath the textbox, there is a submit button. ...

What options are available to enable the user to input information into the v-time-picker component?

I am looking for a solution where users can input digits into the vuetify v-time-picker, while still being able to select the time on the clock. <v-col align-self="center"> <v-menu ref="menuTimeStart" v-model="me ...

Query MongoDB using an OpenWhisk action

Having trouble creating an OpenWhisk action that executes a find query in MongoDB and returns the results? No worries, as I am having difficulty getting it to work correctly. Even though I've connected OpenWhisk with MongoDB properly, I'm still n ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

Need some assistance with regular expressions? Specifically, parsing a list of URLs?

How can I parse various URL structures that may include: protocol://category protocol://category/:id protocol://category/:id#hash For example: protocol://feed > feed protocol://blog/123 > feed, 123 protocol://video/123#ABC > feed, 123, ABC The p ...

Is there a way to protect the privacy of State variables within a Flux Store?

Currently, I've implemented my own version of the Flux pattern in a small scale in order to deepen my understanding of the concept. So far, it's been working well and I've been gaining valuable insights! However, I've encountered a chal ...

The Vue page is failing to display the updates

I am facing an issue with my multilingual site that uses Vue.js & Laravel. The translated page for vue is not displaying any changes. Here is the code snippet from my app.js: import VueI18n from 'vue-i18n'; import Locales from './vue-i18 ...

Executing javascript code that has been inserted into inner HTML is not functioning as expected

Trying to retrieve a response from another page, specifically named ajaxresponse.php, through an AJAX request. I also aim to execute some JavaScript actions on that ajaxresponse.php page, but the JavaScript code is not functioning as expected. Although I a ...

Can you create reusable components in Wordpress that are encapsulated?

In my quest to explore innovative approaches to Wordpress theme development, I have stumbled upon a variety of options such as the "Roots Sage" starter theme, the "Themosis Framework," and "Flynt." While these solutions address intriguing problems, they do ...

What is the best way to create a new object in a Vue component with optimal efficiency?

Currently, I am working on initializing a map that would be utilized in my calculatePrice function. calculatePrice(key) { let prices = new Map({ 0: 17, 1: 19, 2: 24, 3: 27, 4: 30, 5: 46, 6: 50 ...

What is the method for retrieving a module from a store using its name represented as a string?

Just starting out with Vuejs and encountering a slight hiccup. I want to utilize a store, however, all I have is the name stored as a string. From what I understand, I can access the method (all()) of the store by using: storeName.all My issue lies in ha ...

Ways to implement jsdoc on vue3 props without utilizing typescript?

const props = defineProps({ items: { /** @type {{new(): Color[] }} */ type: Array, required: true, }, selectedColor: { type: Object, required: true, }, composable: { type: Function, required: true } }) We do not use T ...

Is there a way to copy this JavaScript variable and modify the displayed text?

I am working on a JavaScript code that is used to create a basic news page with a filter from a mySQL database. The code generates the heading, main content, and date created for each news item. I now need to add a "read more" link at the bottom of each ne ...

Performing API requests in NextJS using Prisma on a client-side page

Currently, I am faced with a challenge in fetching data from my database on a NextJS page designated as a client page using "use client" as required by the theme I am working with. At the moment, I have a page that fetches data from the database and redire ...

Ways to conceal an animated gif once it has been downloaded?

Is it possible to have an animated gif image vanish once server-side Java code runs and the client receives an HTTP Response from the webserver without relying on Ajax? I am currently utilizing the following Struts2 submit button: <s:submit value="sho ...

The link in Next.js is updating the URL but the page is not refreshing

I am facing a peculiar issue where a dynamic link within a component functions correctly in most areas of the site, but fails to work inside a specific React Component - Algolia InstantSearch (which is very similar in functionality to this example componen ...

Creating a dropdown list for months in Vue.js

I have managed to get this working in my test project, but I'm struggling to understand the inner workings of it. The Vue.js implementation seems a bit complex to me, and I believe there might be a simpler way to achieve the same result. Any advice on ...

Should data be stored in HTML5 using data-* attributes?

I have encountered a scenario like this: The screen contains numerous 'Rocks', each with attributes such as weight, points, and velocity. When a rock is clicked, its attributes are displayed. Currently, I have stored all the rocks' attribu ...

Using Node.JS to read a huge file and inserting each line individually into a database

Dealing with a huge file containing over 100K JSON Strings, each on a separate line is proving challenging. My goal is to read each line, insert it into one database, and update another document in a different database with basic information from the initi ...