Vue 3 Options API makes handling empty this.$refs easy

Previously in Vue 2, I was able to retrieve a property from component children (rendered within a v-for loop) using this.$refs along with a dynamically-assigned :ref attribute.

However, this code no longer works in Vue 3. Upon logging out this.$refs, I noticed that the object is now empty.

My goal here is to access the 'isOrderable' property on all children components. The issue seems to be related to using :ref="product.id" where product.id is a variable. If I change it to ref="foobar", then I can at least get the last child component using this.$refs.foobar. But in Vue 2, I used to receive an array containing all children components.

  <script>
  import productItem from "./Product.vue";
  export default {
    props: ["products"],
    components: {
      'product-item': productItem
    }
    methods: {
      addAllProducts() {
        const orderable = this.products.filter((p) => this.$refs[p.id][0].isOrderable);
        ...
      }
    }
  }
  </script>

  <template>
    <form>
      <div v-for="product in products" :key="product.id">
        <product-item :product="product" :ref="product.id" />
      </div>
      <button @click="addAllProducts">Add All</button>
    </form>
  </template>

There seems to have been a change in Vue 3, but I cannot seem to find any relevant information on it. While there is plenty of documentation on this.$refs with the composition API, it doesn't address my specific issue.

Any assistance would be greatly appreciated.

Answer №1

Vue 3 introduces a new way of working with arrays in refs, requiring a function to be passed and a state on your data to manage the refs. You can find more information about this change here.

If the logic for toggling the orderability of a product-item is contained within the product-item component, consider using an event that emits when the orderability value changes. This event can update an array of orderableProducts with the id of each product, allowing you to utilize multiple v-models options in Vue 3 without the need to hold a reference of the dom for filtering purposes.

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

How can one keep object values constant or unchanging in JavaScript?

Here is a simple example where I need to clarify my requirement. I want to ensure that the values of object a are not changed after assigning it to constant b and modifying its values. I want the console to display the original values of object a, not the ...

Automatically setting the checkbox for each unique ID based on database values for the specified hobby

Query: The issue I am facing is that when I click the edit button for the first time, the checkboxes get checked based on the values in the database table. However, when I click another edit button for the second time, the checkboxes do not get unchecked f ...

I am trying to understand why my React component's render function is being called twice - first without any data and then again with data, resulting in a

I am facing an issue with my TreeNav component, where the data is fetched from an API call. I have set up the reducer, action, and promise correctly, but when I try to map over the data in the component render function, I get an error saying "Uncaught Type ...

React Higher Order Components (HOCs) are functioning correctly with certain components but not

I have encountered an issue where using a Higher Order Component (HOC) to bind an action to various types of elements, including SVG cells, results in unintended behavior. When I bind the onClick event handler normally, everything works fine, but when I ap ...

Is there a way to retrieve a JSON result from an API call using jQuery (or plain JavaScript) without relying on Ajax?

As someone new to JS and jQuery, I am working on building a key-value map from an API call that returns an array of key-value pairs. [{"key":"191","value":244}, ... , {"key":"920","value":130}] I have created the following ajax code in my attempt to achi ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

Ways to refresh UI in ReactJS without triggering a specific event

In my React application, I am displaying various pictures and GIFs that users can attach to a post. Currently, each image has an onClick handler which triggers either a modal with different options or deletes the picture if the user holds down the ctrl key ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Is it possible to use AngularJS promises without callbacks?

Typically, when I want to retrieve data asynchronously, I would use the following approach: var promise = $http.get('/api/v1/movies/avengers'); promise.then( function(payload) { $scope.movieContent = payload; }); This scenario is quite ...

Exploring the power of React Leaflet and the exciting possibilities of React Leaflet

I'm currently in the process of implementing the draw functions on a leaflet map. I started off by creating a new app with just react-leaflet installed. I used npx create-react-app and installed the following packages: npm install react react-dom lea ...

Prioritizing the execution order of useEffect in Next.js

Here is the code snippet from my _app.tsx useEffect(() => { console.log(1) }, []); And this portion of code is from my index.tsx useEffect(() => { console.log(2) }, []); Currently, in the console it prints 21 However, I want it to print 12 ...

Filtering Quantity Based on Specific Attribute in ReactJs

I want to implement a quantity filter that can be based on color, size, or both. For instance, when I select the red color, it should display the total quantity of red items available. However, if I choose both the color red and size small, it should show ...

What is the best method to retrieve the title from an array using javascript?

I am working with a JSON object containing information on thousands of students. I have converted this JSON object into an array, and below is an example of how one array looks: [ 'Alex', { id: '0.0010733333111112', grade: &apos ...

Tips for creating a linear movement effect for a collection of objects

I am working on animating a linear gripping motion for picking and placing objects. Here is a codesandbox link where you can see the issue I am facing: https://i.sstatic.net/dUdPv.png The gripper is created, moves down to reach the LEGO brick, and then s ...

Explore three stylish ways to showcase dynamic JavaScript content using CSS

Objective: For Value 1, the CSS class should be badge-primary For Value 2, the CSS class should be badge-secondary For all other values, use the CSS class badge-danger This functionality is implemented in the handleChange function. Issue: Current ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Is there a way to configure Cordova to utilize Yarn JS instead of NPM when installing plugins?

Updated Question: When adding plugins to my Cordova project, I currently use the command cordova plugin add x, which I believe utilizes npm in the background. Is there a way to switch out npm for Yarn within Cordova? This change would greatly impact cach ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...

An AJAX request will only occur if there is an alert triggered on a particular computer

Here's an interesting issue I encountered with my company's CMS newsletter system. It seems that the AJAX call to send an email works flawlessly in all modern browsers and operating systems, except for one client. This particular client is using ...