Enhance your Vue3 experience by appending values to arrays or proxies!

My current project involves creating an app where users can list IP addresses, with the ability to add as many as they want. Starting with one input field, clicking a + button should display an additional input field for the user. I aim to store these IP addresses in an array for later looping purposes. Vue 3 complicates things by turning my basic array into a proxy. Despite trying to grasp how proxies work (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), I can't figure out how to simply append an item to the array (or proxy). While using v-for to generate input fields based on array items is functional, that's not the issue at hand.

The initial code snippet looks like this:

export default {
  data() {
    return {
      addresses: ["192", "193"],
    };
  },
  methods: {
    addIp() {
      this.addressses.push(194);
      // Using 194 as an example, but ideally, the new item should be empty
    },
}

To my surprise, adding 194 to the end of the array doesn't seem to work as intended. Upon logging this.addresses, it now returns a proxy - meaning Vue transformed my array into a proxy. Although this change seems acceptable, pushing items to the proxy array isn't functioning as expected despite consulting resources on the matter (How can I push to an array (in Vue 3)?).

Attempting this.addresses.push({2: 194}) to force the item into the second position only led to breaking my code.

Key questions arising from this dilemma include:

  1. Is converting the array to a proxy necessary? If so, why?
  2. What am I overlooking or doing incorrectly when attempting to modify a proxy?
  3. In the future, how can I effectively loop through a proxy?

EDIT:

<template>
<form class="serviceForm" @submit.prevent>
<div class="serviceFormServiceAddress">
  <div class="ipButtons">
    <label for="ipAddress">IP Address</label>
    <button @click="removeIp">-</button>
    <button @click="addIp">+</button>
  </div>
  <input
    type="text"
    v-for="(address, index) in addresses"
    :key="index"
    v-model="addresses[index]"
    name="ipAddress"
    class="ipAddress"
  />
  <!-- Change name to different IDs -->
</div>
</form>
<button @click="generateServiceList">Test services</button>
</template>

The provided code dictates the generation of input fields. Utilizing the console to monitor array values and additions upon pressing the + button seems crucial. Should such checks occur elsewhere, and if so, where?

Answer №1

If my understanding is correct, please refer to the code snippet below:

const app = Vue.createApp({
  data() {
    return {
      addresses: ["192", "193"],
      ip: ''
    };
  },
  methods: {
    addIp() {
      this.addresses.push(this.ip);
      this.ip = ""
    },
  }
})
app.mount('#demo')
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d3d0c0e5968b978b979c">[email protected]</a>/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(address, i) in addresses" :key="i">
    {{ i + 1 }}<input v-model="addresses[i]" />
  </div>
  <input v-model="ip" />
  <button @click="addIp">Add</button>
  <p>{{ addresses }}</p>
</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

Failure to Link Different Files Using HTML Links

Organizing the different pages of my website, I initially stored HTML files in a folder called X, with index.html, main.html, and other pages. To streamline access, I decided to separate the articles into folders A, B, and C within folder X. However, this ...

Cypress encounters a SyntaxError while running in continuous integration due to an unexpected token 'export' with the cypress-io/github-action@v2 typescript

Within my cypress plugin file located at frontend/cypress/plugins/index.ts, I have the following code snippet: export default ((on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config }) ...

Chokidar operates smoothly from the command line, but fails to function properly when invoked through the use of 'npm run'

I've implemented a script that monitors Tailwind CSS files using Chokidar. The script works perfectly when I execute the command in the CLI using chokidar 'tailwind.config.js' --initial=true -c 'npm run build-tailwind'. It successf ...

Tips on using Bootstrap 4 containers within a container-fluid and ensuring text stays within a container at all times

What is the best way to incorporate a Bootstrap 4 container within a container-fluid? how can we ensure that text is always contained within the blue section? ...

Trouble encountered when attempting to programmatically dismiss a modal following a confirmation alert

When the user clicks on the close button, I want to display a confirmation alert to confirm if they really want to close the modal. However, I have encountered an issue with hiding the modal and preventing it from being hidden in the two solutions that I h ...

Transferring data from a database to a Vue component and storing it in a variable

I've encountered an issue while attempting to retrieve a value from my database and then store it in a variable within my Vue Component. The data retrieval process is successful, but I encounter an error when trying to assign that value to a variable ...

Show a loading icon as the synchronous Ajax request is being sent

Seeking a way to show a spinner while making a synchronous Ajax request to fetch data from the server. Acknowledging that asynchronous mode is preferred, but not permitted in this case. Aware that a sync ajax request can cause browser blocking. An attemp ...

Can you explain the significance of the <%= %> HTML tag?

I've recently been tackling a project with Webpack. For those not familiar, Webpack is a bundler that combines all your files into one final product. One task I encountered was trying to insert one HTML file into another, similar to an import or requ ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

Implement custom sorting for a single column in a vuetify 2.3+ table

Struggling to comprehend the custom-sort documentation for v-data-table in Vuetify. I am confused about the customSorters?:. More information can be found here. I intend to only use custom-sort when the column row is 'updated_at' or 'create ...

Seeking information on how to make a request through a Nodejs Proxy Server?

I've set up a Nodejs Proxy server that looks like this: `var http = require('http'), httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer({}); proxy.on('proxyReq', function(proxyReq, req, res, opt ...

What is the best way to preserve the state of child components after being filtered by the parent component?

I've been working on a small application using create react app to enhance my skills in React, but I've hit a roadblock with managing the state. The application maps through JSON data in the parent component and displays 6 "image cards" as child ...

IE compatibility mode causing ckeditor dropdown to be hidden

When using the CKEditor editor bar inside a green div with another div below it, I noticed that when clicking on "font" or any other option that opens a dropdown menu, it gets hidden behind the bottom div. This issue seems to occur in browsers like Chrome ...

When submitting a form in HTML, ensure that the input checkbox returns 'On' instead of 'True'

My MVC3 app is using Project Awesome from http://awesome.codeplex.com/, but I'm encountering a strange issue with checkboxes. Inside a Modal popup, I have the following simple Html code: <input type="checkbox" class="check-box" name="IsDeleted"> ...

Ways to choose a Gmail account for logging into Firebase on mobile applications using Vue for a cross-platform application

Currently, I am developing a cross-platform app for iOS and Android that utilizes a .vue view to handle authentication via Gmail on Firebase. My approach involves using Google as the provider: provider = firebase.auth.GoogleAuthProvider() firebase.auth().s ...

JSON object containing multiple elements in JavaScript

I have a JavaScript JSON object const student = { name: "bob", age: 7, grade: 6 } and I can send it to my Web API using the axios POST command with JSON.stringify(student) To build multiple student objects from an array by looping through and p ...

How do I retrieve the date from a dynamically generated text field within an ng-repeat loop and pass it

I have a specific issue with accessing the value of dynamically created input text in my web form. The problem arises when using ngRepeat to manage items, particularly with $scope.newValueItem being undefined. How can I retrieve the value from dynamically ...

Storing information in a database via a web API using AngularJS

I am new to the world of AngularJS and Web API. I am currently facing challenges when trying to send data to a database through Web API and Angular. I have successfully managed to load JSON data from the Web API. Any assistance on this matter would be grea ...

Exploring the depths of a JSON data structure

Newbie Alert: I'm dealing with a JSON response that triggers a .on('click') function and it looks like this: {"1411939719-8696.jpeg":true} My goal is to delete a row in a table based on the source of the call, but for some reason, it&apos ...

The ability to retrieve variables within a certain scope from a function that is declared externally

Is there a method to access and print the value of a closure variable, temp, from a function defined outside the closure but referenced within it without passing temp as an argument to the function? var funcA, funcB; funcA = function () { console.log( ...