issue with non-existent value in v-for loop when using functional template refs

Scenario

I am currently developing a personalized filtering feature. This feature allows users to add n filters that are shown using a v-for loop in the template. Users have the ability to modify input values and remove filters as needed.

Challenge

Issue arises when removing a filter, where my array itemRefs ends up with a null value for the last item.

Code (simplified)

<script setup>
const filtersScope = $ref([])
const itemRefs = $ref([])

function addFilter () {
  filtersScope.push({ value: '' })
}

function removeFilter (idx) {
  filtersScope.splice(idx, 1)
  itemRefs.pop() // <- necessary? has no effect
  // validate and emit stuff
  console.log(itemRefs)
  // itemRefs got at least one null item
  // itemRefs = [null]
}

// assigning values from input fields for future use
function updateValue() {
  itemRefs.forEach((input, idx) => filtersScope[idx].value = input.value)
}
</script>

<template>
  <div v-for="(filter, idx) in filtersScope" :key="filter.id">
    <input 
      type="text" 
      @keyup="updateValue" 
      :ref="(input) => { itemRefs[idx] = input }" 
      :value="filter.value"
    >
    <button @click="removeFilter(idx)" v-text="'x'" />
  </div>
  <button @click="addFilter()" v-text="'add filter +'" />
</template>

>>> View Demo

to replicate:

  1. Add two filters
  2. itemRefs will now store the template refs as follows: [input, input]
  3. Remove one filter, resulting in itemRefs looking like: [input, null]
  4. Remove the last filter, leaving itemRefs as: [null]

Inquiry

Even after adding itemRefs.pop(), I encountered an error when applying new filters after removal:

Uncaught TypeError: input is null

While the pop() method prevented a console error, the inclusion of null in itemRefs still persists.

How can I properly clean up my template references?

Answer №1

It's puzzling to see the use of $refs within another $refs, as it doesn't seem to function as expected.

Nevertheless, nesting $refs is generally unnecessary. When modifying data, focus on updating the outermost $refs. Utilize $computed to obtain a simplified view of that data.

For a working illustration, check out this a functional example.

<script setup>
  const filtersScope = $ref([])
  const values = $computed(() => filtersScope.map(e => e.value))

  function addFilter() {
    filtersScope.push({ value: '' })
  }

  function removeFilter(idx) {
    filtersScope.splice(idx, 1);
    console.log(values)
  }
</script>
<template>
  <div v-for="(filter, idx) in filtersScope" :key="idx">
    <input type="text" 
           v-model="filtersScope[idx].value">
    <button @click="removeFilter(idx)" v-text="'x'" />
  </div>
  <button @click="addFilter()" v-text="'add filter +'" />
</template>

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

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

Verifying the presence of an image via its URL may not be functional across all browsers

Hey folks, I'm working on a project that involves displaying an image along with other fields in a loop where the image source changes with each iteration. I also need to check if the image exists and set a default source if it doesn't. The code ...

Puppeteer failing to detect dialog boxes

I'm attempting to simulate an alert box with Puppeteer for testing purposes: message = ''; await page.goto('http://localhost:8080/', { waitUntil: 'networkidle2' }); await page.$eval('#value&apos ...

Ways to customize parent element when child has a specific class in Vue?

What is the best way to style a parent div if the child has a specific class? I attempted using computed properties with $refs, but I always get an undefined value for $refs.[class] Example <div :style="isChildHasClass" class="container"> < ...

AngularJS closes when clicked outside

I've been attempting to add a close on outside click functionality to my code, similar to this example: http://plnkr.co/edit/ybYmHtFavHnN1oD8vsuw?p=preview However, I seem to be overlooking something as it's not working in my implementation. HT ...

Encountering an issue with Server Side Rendering in React Router Dom where an error message pops up saying: "Warning: React.createElement: type is

Specific Error: A warning has occurred: React.createElement: the type provided is invalid -- it was expecting a string (for built-in components) or a class/function (for composite components), but instead received an object. in Posts in Connect(Po ...

Exploring Material UI: Customizing the styling of components within TablePagination

Is it possible to customize the styling of buttons within the actions panel of the TablePagination component? import { withStyles } from '@material-ui/core'; import MuiTablePagination from '@material-ui/core/TablePagination'; const st ...

Version 1.0 and higher of Ionic do not display the side menu when using tabs

I have developed an app using Ionic that includes a side menu with tabs feature. The side menu displays correctly when using Ionic version 0.9.27, but it does not show up when the version is 1.0 or higher. What could be causing this issue? HTML Layout & ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

Converting a VueJS application with node/express into a single container using Docker

I may be treading on familiar ground here, but I haven't come across a solution that addresses my specific issue. I have a VueJS application running with Express/NodeJS as the server, and while I know the recommended approach is to separate them into ...

What is the best way to set a value in PHP that can be utilized as flight plan coordinates on a Google Map within my script?

I am looking to dynamically update the content of my div with id "map" in response to button clicks, where the flight plan coordinates are changing. Currently, I have attempted to achieve this by assigning PHP output to a JavaScript variable as shown below ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

Challenges with Organizing Data and Maintaining Database Integrity

I have been working on making this sortable code function properly. Initially, I had it working fine with <li> elements as shown in the UI examples. However, now I am trying to implement it with <div> elements. While it shouldn't be much o ...

Swapping icons in a foreach loop with Bootstrap 4: What's the most effective approach?

I need a way to switch the icons fa fa-plus with fa fa-minus individually while using collapse in my code, without having all of the icons toggle at once within a foreach loop. Check out a demonstration of my code below: <link rel="stylesheet" href= ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

Utilizing JQuery to alter the text color if validation fails when entering a value

Is there a way to change the text in the input box to red when PHP validation fails using JQuery? I had success with Javascript, but it kept disappearing every time I clicked submit... <form class="link-form" method="post" action=""> <la ...

What causes the AngularJS variable to receive a null value following an HTTP request?

Using AngularJS on the frontend, I have a variable named ttest defined before making an $http call. Subsequently, data is assigned to this variable. The value of ttest[0] is available within the $http function but not outside of it. angular.module(&apos ...

Organize every rectangle and text element in D3 into distinct groups

Currently, I am working on creating a bar graph using d3.js. The goal is to display text on top of each bar when the user hovers over it. To achieve this, the <text> and <rect> elements need to be grouped inside a <g> element. For Exampl ...