Mastering the Art of Dynamic Refs in Vue 3's Composition API

I am currently facing a challenge with utilizing dynamic refs in the Vue Composition API. According to the Vue documentation, it suggests using the following approach:

<div v-for="item in list" :ref="setItemRef"></div>
import { onBeforeUpdate, onUpdated } from 'vue'

export default {
  setup() {
    let itemRefs = []
    const setItemRef = el => {
      if (el) {
        itemRefs.push(el)
      }
    }
    onBeforeUpdate(() => {
      itemRefs = []
    })
    onUpdated(() => {
      console.log(itemRefs)
    })
    return {
      setItemRef
    }
  }
}

However, in my simplified code snippet below:

<template>
    <section
      v-for="(item, i) of storyList"
      :ref="(el) => { if (el) { divs.push(el) } }"
    />
</template>

<script lang="ts">
[...]
export default defineComponent({
  props: {
    storyList: {
      type: Array as () => StoryList,
      required: true,
    },
  },
  setup() {
    const divs = ref([])
    
    return { divs }
  },
})
</script>

... I observed only the following output in my Vue Dev Tools:

data:
divs:Array[0]

$refs:
function(el) { if (el) { _vm.divs.push(el) } }:Array[4]
0:<section id="story-0" class="story-item">
1:<section id="story-1" class="story-item">
2:<section id="story-2" class="story-item">
3:<section id="story-3" class="story-item">

This results seems off, doesn't it? I should be accessing the refs from divs, rather than $refs (which is not functional in vue 3), correct?

Answer №1

If you need reactivity for an array, make sure to utilize the following code snippet: reactive([])

Answer №2

Implement a dynamic approach to manage the setItemRef

For additional information, check out this article

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

Improve the translation animation on an element containing numerous child nodes

Looking for ways to enhance the smoothness of the transition in the "infinity list" animation. While it's just a demo at the moment, the real app will have various elements emerging from each "pin". The main performance bottleneck seems to stem from t ...

How to extract a subset of data from an existing object and create a new object in Vue JS

My latest project involves creating a search app to find products. I have implemented a PHP script that returns results in JSON format when a keyword is submitted. The data retrieval is done using axios. The challenge I am facing is with handling the disp ...

What is the best way to create a new row within a Bootstrap table?

Struggling to format an array inside a table with the `.join()` method. The goal is to have each car on a separate row. Attempts using `.join("\r\n")` and `.join("<br />")` have been unsuccessful. What am I overlooking? ...

Conditionally render a component only if a calculated property is not activated

When the state preference in my vuex store changes, I need to update the DOM by calling the checkValue method each time. This is how my index.html looks like: <div id="app"> <my-component></my-component> <my-other-component&g ...

Is Vue instance created if element is present?

I am currently developing an application where some pages contain Vue instances, while others do not. My issue arises when switching from one page to another, and the following warning message appears: [Vue warn]: Cannot find element: #element-id How can ...

Determine if the user has liked the post using VUEJS

I need to verify whether the user has already liked the post. I have an array containing the users who have liked the post, but I'm unsure how to hide the button if the logged in username is present in the likes array. Here's the relevant code sn ...

Dynamic routing with Vue

Currently in the process of developing an application and encountering an issue with my code pertaining to dynamic routing. Utilizing Firebase to fetch data for the app, each department in the database should generate a navbar. Upon clicking on a specific ...

Using Vue.js to showcase a data table in either a grid or list view

Currently, I am diving into the world of vue.js while also sharpening my skills in javascript. My goal is to showcase a data table in list view and show folder images in grid view. However, I'm struggling with making it happen. Any guidance or assista ...

Guide to fetching and displaying a PDF file in the browser using Vue.js and Axios

Despite successfully using Axios to download a pdf file on the browser with correct page numbers and orientation, the content appears to be empty. Here is the API code snippet: [HttpGet] [Route("~/api/Document")] public HttpResponseMessage Get(in ...

I'm having trouble launching the Vue UI after successfully installing the Vue CLI - any ideas why?

After installing the following versions: node 8.11.2 npm 6.3.0 I proceeded to install the Vue CLI (@vue/[email protected]): npm i -g @vue/cli However, upon running the command below: vue ui An error message was displayed as follows: Error: Cann ...

Please refrain from displaying the user table data in the View page source under any script tags

When I access the user data in the script tag of my app.blade.php file, the page resources show this line of code. 'window.user = {"id":2,"name":"test","email":"hidden_email@example.com","email_verified_at":null,"created_at":"2021-03-02T04:52:43.0000 ...

What are some tips for utilizing the "bottom-row" slot within the "b-table" component in bootstrap-vue?

I am working on a component that utilizes the bootstrap-vue b-table component. My goal is to create a bottom row that displays the sum of each column in the table. However, I encountered an issue where the bottom-row only fills the first column, leaving ...

Instructions on utilizing the signUp() function in Supabase for including extra user details during the registration process

My latest project involves building a Vue.js application with authentication using Supabase. I've been trying to implement the signUp() method from Supabase in order to collect extra user data during the sign-up process. In my code, I added a property ...

Tips for handling the user's logged-in status in NativeScript Vue

I had a question about managing user login/logout, so I tried the following approach: store.commit('load_state'); store.subscribe((mutations, state) => { ApplicationSettings.setString('store', JSON.stringify(state)); }); new Vue( ...

Dependency tree resolution failed during VUE installation

After pulling my project from another computer where it worked fine, I encountered an error when trying to npm install on this machine. Can someone please provide some guidance on how to resolve this issue and prevent similar problems in the future? npm ER ...

Could you offer guidance on incorporating a component into a Vue route?

I am attempting to integrate a vue component called <channel-card></channel-card> into my home route, but I am encountering multiple errors. Main.js const router = new VueRouter({ routes: [ {path: '/home', component: home} ] ...

Guide on how to verify user identities with Azure AD in a Vue.js interface and backend developed with .Net 5

Our team is currently in the process of transitioning from .Net MVC to a Vue.js front-end. We had originally implemented a custom Attribute in our MVC version that utilized Azure AD for user authentication on specific pages. This attribute verified if user ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

A guide on how to access a Vue data property within another data property

I am delving into Vue.JS and facing an issue where every time I try to reference the dashboards property from the currentDashboard data expression, it returns 'dashboards is not defined'. Could it be possible that Vue is evaluating the currentDas ...

What are the steps to develop a Vue application with a built-in "add to desktop" functionality?

Looking to develop a Vue application with the feature of adding to desktop, similar to the option near the share button on YouTube. Any suggestions on how to achieve this? https://i.stack.imgur.com/nXG4i.png ...