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:
- Is converting the array to a proxy necessary? If so, why?
- What am I overlooking or doing incorrectly when attempting to modify a proxy?
- 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?