Exploring the functionality of a dynamic array in Vue.js 3

In my Vue.js 3 (beta) project, I have created an array using the reactive function in order to bind its items to various UI components through a loop. This setup has been successful thus far.

However, I now face the challenge of updating a specific value within this array. Due to the fact that Vue.js proxies the array, attempting to use methods like find or findIndex directly on it does not yield the desired results; the proxy complicates things as it's not just a straightforward array.

To work around this issue, I decided to first get a raw copy of the array using toRaw, perform the search operation with findIndex on the copy, and then update the original array using the index obtained. While this method does achieve the desired outcome, it doesn't feel like the most elegant solution.

Can someone suggest a more efficient approach to tackling this problem?

PS: I am specifically looking for solutions that are compatible with Vue 3, so any advice pertaining to Vue 2.x is not necessary in this case.

Answer №1

All of the array's functions remain accessible via the Proxy, allowing you to utilize methods like find and findIndex:

import { reactive } from 'vue'

const items = reactive([1,2,3])

console.log(items.find(x => x % 2 === 0))
console.log(items.findIndex(x => x % 2 === 0))

const MyApp = {
  setup() {
    const items = Vue.reactive([1,2,3])
    
    return {
      items,
      addItem() {
        items.push(items.length + 1)
      },
      logFirstEvenValue() {
        console.log(items.find(x => x % 2 === 0))
      },
      logFirstEvenIndex() {
        console.log(items.findIndex(x => x % 2 === 0))
      },
      incrementItems() {
        for (let i = 0; i < items.length; i++) {
          items[i]++
        }
      }
    }
  }
}

Vue.createApp(MyApp).mount('#app')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ccbab9a98cffe2fce2fce1beafe2f9">[email protected]</a>"></script>
<div id="app">
  <button @click="logFirstEvenValue">Display first even item</button>
  <button @click="logFirstEvenIndex">Display index of first even item</button>
  <button @click="incrementItems">Increase items</button>
  <button @click="addItem">Add new item</button>
  <ul>
    <li v-for="item in items">{{item}}</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

Converting an object to an array with the help of jQuery

I have been working with a json file and created an object using jquery's $.get method. Here is what it looks like when I log it: console.log(array); [Object, Object, Object, Object, Object, Object, Object, Object] 0 : Object country ...

Utilize a JSON object with ChartJS for data visualization

Recently, I've been working with a REST API that returns historical data in the following format: { "2021-6-12": 2, "2021-6-13": 3, "2021-6-14" :1 } This data represents the count of measurements taken on each date ...

Tips for incorporating nonce or sha into the connect-src directive in Content Security Policy (CSP)

Can a nonce be used in an API request to make sure that the connect-src in CSP doesn't flag it as a malicious address? It appears that nonce can only be used in script-src or style-src, not in connect-src. So far, I have only been able to list URLs ...

Utilizing Node.js for Lambda Functions

I am attempting to retrieve a list of all EC2 instances in a specific region using a lambda function. Below is the code snippet I am using: const AWS = require('aws-sdk'); AWS.config.region = '******'; exports.handler = async function( ...

The React SwiperJs autoplay feature seems to be malfunctioning, as the swiper is not automatically

I have been utilizing the Swiper component in React from this link. However, I encountered an issue with setting it to autoplay as it doesn't auto swipe. Here is my attempted code: // Resource: https://swiperjs.com/get-started/ import React from &apos ...

The error message states: "Cannot create element as the React object is not

Recently delving into the world of React and Material UI, I've been working on creating an AppBar with nested Tabs. Here's a snippet of my current approach: import {React, PropTypes, Component} from 'react'; import TodoTextInput from & ...

The login page allows entry of any password

I'm running a xamp-based webserver with an attendance system installed. I have 10 registered users who are supposed to log in individually to enter their attendance. However, there seems to be an issue on the login page where any password is accepted ...

JavaScrip $("").text(); is a straightforward way to recognize and extract

At the moment, I am utilizing the jQuery script below: $("TD.info > font").text(); when this specific HTML structure is present on a webpage: <td class="info"> <font> 3001474535 </font> </td> I had the idea to tweak t ...

The recursive component is functional exclusively outside of its own scope

I'm facing an issue where my recursive component is not nesting itself properly. The problem arises when I try to use the Recursive component inside another Recursive component. Although the root is correctly inserted into the Recursive component fro ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

The art of creating an asynchronous function: A comprehensive guide

My goal is to download files from a Firebase bucket and then store them in a database. I need the download process to be asynchronous, ensuring that each file is fully downloaded and added to an array before moving on to the next one. However, my current ...

Using Laravel's compact function within Vue components

I am wondering how to pass variables to a Vue component in Laravel? When using blade, we can pass variables like: $now = Carbon::now(); return view('xxxxxxxx', compact('now'); This allows us to use $now in the xxxxxxxx blade file. Bu ...

Looking to display or conceal several divs according to the option selected from a dropdown menu?

I've been searching for a solution to my simple dropdown issue, but haven't had any luck in the forums. This is the code for the dropdown: <select id ="category_faq"> <option value="1">item1</option> <option value= ...

Using Docker to containerize a Vue single-page application, with the flexibility to switch API URLs based on the environment

I have a dockerized Vue.js application that communicates with an API hosted on a java backend. The API URL varies depending on the environment - it's app.example.com/api in production, staging.example.com/api in staging, and localhost:8081 when runnin ...

Tips for sending Json data through a form to a controller and storing it in a database

I am working on a form that contains a sample table with values. The table (id=sampleTbl) has two columns: name and age. My goal is to save this data into my database table named person (id=AI, name, age) when the submitButton (id=idOfButton) is clicked. ...

Ways to host static content in ExpressJS for specific directories and exclude others

I need to configure my ExpressJS server to serve static files from specific paths only, excluding others. For example, I want to serve static files from all paths except /files where I only need to manipulate a file on the server. Currently, my code looks ...

JavaScript encountered an issue as it attempted to reference the variable "button" which was

I am currently working on developing a new API, but I have encountered some issues with JavaScript: Below is my JS/HTML code snippet: const express = require('express'); const app = express(); const PORT = 3000; submit.onclick = function() ...

Adjusting the color of a box in Threejs through dat.gui.min.js controls

I want to enhance the user experience by allowing them to choose a color from the HEX menu and update the color of the box in the scene using UI controls. Below is the JavaScript code I have implemented for this purpose: // author: Arielle Mueller // date ...

JavaScript validation for a form dynamically generated within a table

NOTE: Utilizing Foundation 6 along with the Abide Form Validation. I'm currently working on implementing automatic form validation for a website. The approach I've taken involves creating a table (using the jQuery Datatables library) with multip ...

Encountered an issue while constructing swagger in Laravel project using Vite

After running npm run build in Laravel, I encountered the following error. Interestingly, everything works fine when I run npm run dev. However, the error below occurs during the build process: rendering chunks (2)...warnings when minifying css: ▲ [WARNI ...