Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  85] [ 4]  / answers: 1 / hits: 8321  / 3 Years ago, sun, march 21, 2021, 12:00:00

In Vue 2 I used to be able to access a property on component children (rendered inside a v-for loop using this.$refs and a dynamically-assigned :ref).


The same code in Vue 3 fails, and when I log out this.$refs the object is empty.


Here I'm wanting to access an 'isOrderable' property on all children. The problem appears to be with :ref="product.id" being a variable. If I change it to ref="foobar" then I do get the last child in this.$refs.foobar. But it vue2 me an array back 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>

Obviously something changed in vue3 but I can't find any info about it. There's plenty of info on this.$refs, and but it all has to do with accessing refs from the composition API.


Any help appreciated.


More From » vue.js

 Answers
2

In vue 3 they change how refs work with arrays, now you need to pass a function and have a state on your data to keep track of your refs https://v3-migration.vuejs.org/breaking-changes/array-refs.html#frontmatter-title.


I don't know how your code is structured but maybe there is a better solution to your problem than using refs, if the logic that toggles if a product-item is orderable lives inside the product-item component you can have an event that emits when the orderable value is changed an update an array of orderableProducts with the id of each product, you can even use that in a v-model with the multiple v-models options of vue3. in that way you don't need to hold a reference of the dom just to filter by the ones that are orderable.


[#1615] Tuesday, March 16, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
benitoh questions
;