Vue's v-for loop items experiencing delayed updates

In order to better understand and clarify, I will break it down into smaller points.

  • First, I am able to highlight text using my mouse or trackpad. The highlighted text is then stored in an array of objects upon release of the mouse button. Each object within the array contains the selected text.

  • My goal is to loop through this array so that each selection can be displayed one after the other until different text is selected.

Essentially, every time a text is selected, it is stored in the selectionArray as a string inside an object. Therefore, selectionArray becomes an array of objects structured like this: Upon first selection,

[
 {selectedText: '...string...'}
]

Upon second selection, the array gets updated:

[
 {selectedText: '...string...'},
 {selectedText: '...another string...'}
]

And so forth... To display the selections live, I loop through the items array which is equivalent to selectionArray with:

this.items = selectionArray

I have almost achieved the desired outcome, but there seems to be some missing piece as the modifications are not reflected live. It requires making unnecessary changes in the HTML to see the result. My suspicion lies on the created method, and I would appreciate any logical guidance for troubleshooting. Thank you.

Here is the provided code for reference:

<template>
  <main class='wrapper'>
    <section class='wrapper-copy'>
      <div class='copy'>
        <!-- Inserted Lorem Ipsum content -->
      </div>

    </section>
    <article class="wrapper-select">
      <div class="select">
        <div id='input'
             class='selected-copy'
             v-for='(item, index) in items' 
             :key='item.index'>
          <div class='index'>{{ index }} </div>
          <p class='selection'> {{ item.selectedText }} </p>
        </div>
      </div>
    </article>
  </main>
</template>

<script>
  export default {
    name: 'app',
    data () {
      return {
        items: []
      }
    },
    created () {
      var selectionArray = []
      function storeSelection () {
        var selectedText = window.getSelection().toString()
        if (selectedText.length && selectionArray.indexOf(selectedText) === -1) {
          selectionArray[selectionArray.length] = {selectedText}
        }
        console.log(selectionArray)
      }
      document.addEventListener('mouseup', storeSelection)
      this.items = selectionArray
      console.log(this.items)
    }
  }
</script>

Answer №1

Vue struggles to detect changes in array items and object properties when they are added or deleted. Refer to the Caveats section of the Vue guide for tips on how to work around this issue.

This is what the guide advises:

Because of JavaScript's limitations, Vue cannot automatically detect these array changes:

  1. Directly setting an item using its index, e.g. vm.items[indexOfItem] = newValue
  2. Modifying the length of the array, e.g. vm.items.length = newLength

To address caveat 1, you can use either of the following methods instead of directly setting the item with the index, as they will also trigger updates in the reactivity system:

// Vue.set
Vue.set(example1.items, indexOfItem, newValue)

// Array.prototype.splice
example1.items.splice(indexOfItem, 1, newValue)

To handle caveat 2, you should utilize splice method like so:

example1.items.splice(newLength)

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

Multiple loop in Node.js with Selenium

I just completed a node script using selenium webdriver for automated testing purposes. Below is the code snippet: var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until, _und = require('unders ...

What is the best way to update a BehaviorSubject holding an array without replacing the entire array?

When it comes to adding items to an array BehaviorSubject, the common practice is to assign a copy of the entire array along with the new item using next(). However, I am looking for a way to push items into this array without having to assign a full copy ...

Changing the map behavior when it is moved in Leaflet

I am currently using Leaflet to design a map that includes a personalized sound layer. Each tile on the map features an <audio> element, and I am exploring methods to adjust the audio playback as the user navigates around the map (specifically by mod ...

Deleting the last element of an array in V8 C++ can be accomplished using

Currently, I am developing a native NodeJS module for NodeJs and one thing I am stuck on is how to remove the last element from an array. Local<Array> nodes = Array::New(); I've attempted using nodes->Remove(), nodes->Splice(), nodes-&g ...

Develop a JavaScript regular expression in C# by implementing escape characters

Imagine this scenario: Users enter a keyword (e.g. hello) in my asp.net mvc application and click search. In the C# code, I create a JavaScript RegExp string (/hello/i), which is then used in a query to search MongoDB. The query looks like this: db.Posts. ...

The update function in my Vuejs3 project is not functioning as expected when trying to use JSON data to populate the

Recently, I started working with vuejs 3 and json. My goal is to update a course, however, despite my efforts, the fields for the course (title and content) remain empty with no errors being displayed. In views/blog/OnePost, I am passing the ID of the cour ...

In version 81 of Three.js, the toShapes() function has been relocated to a new class. Find out how

After updating Three.js from v73 to v81, I encountered the following error: Uncaught TypeError: path.toShapes is not a function Upon reviewing the new release notes, I discovered the following changes made to Path: The removal of .actions (yay) Movin ...

A guide on using key arrows in JavaScript to navigate and focus on elements

When working on my HTML project, I have a list of elements that I want to be able to select using the arrow keys. I've included my code here for reference: [http://jsfiddle.net/T8S7c/] What I'm trying to achieve is when the arrow keys are press ...

Determining browser compatibility with TokBox - a guide

Can Tokbox detect browsers and display a "not supported" page? I noticed in Tokbox's demo video page that they are able to do this, but I searched their documentation and couldn't find instructions on how to achieve it. Can anyone provide assist ...

Encountering the error message "ReferenceError: parsePayload cannot be accessed before initialization"

Check out this code snippet: Experiencing an issue with 'ReferenceError: Cannot access 'parsePayload' before initialization' Any assistance would be appreciated const express = require("express"); const { createToDo, updateToD ...

Display a specific number of page indicators on the Flickity plugin

Currently, I am utilizing the flickity plugin to create a slideshow feature on my website. My goal is to display navigation dots on the images to facilitate user interaction. If you are interested, you can access the plugin through this link: I would lik ...

best practice for sending both header and body in angular

Can anyone help with passing both header and body together in a single put request in Angular? const httpOptions = { headers: new HttpHeaders({ 'Authorization': this.login.token }), body: {'fiToDelete': id ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

Issues with converting an Array to a String

As a PHP beginner, I keep encountering the error message "PHP Notice: Array to string conversion" when trying to execute this code provided to me for looping through INSERT statements into a database. I need to iterate through the data due to my use of an ...

What is the best way to display a div based on a keyword match?

If the keyword search results in a match, I can display the corresponding input text and its related category div. Now, I am attempting to also search through category names. If the searched keyword matches a category name, that specific div should be visi ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

Guide to importing a JavaScript module using jQuery

I have been encountering an issue while loading a javascript file using jquery. The code I am working with is as follows: // file application.js $.getScript("module.js", function(data, textStatus, jqxhr) { ... }); Everything seems fine so far. However, t ...

When creating a new instance of a class, I make sure to use the

I am facing an issue when trying to call a function from ClassA within my mainClass, and vice versa. I have attempted using .bind() and .call(), but it only works when I use .bind(this) or .call(this) on functions, not when I try to instantiate a new class ...

removing a specific cookie from the browser's cookies using jQuery

This block of code displays a URL along with a delete image for removing a cookie. The add and display functions are working fine, but I'm stuck on how to implement the delete function. function backLinks(){ var pathname = window.location; va ...

Making changes to a variable within a Service

Hey there! I've been stuck on this code all day and could really use some help. I have a simple textbox that interacts with a controller to update a variable inside a service (which will eventually handle data from elsewhere). Currently, I can retri ...