[Vuejs]-Getting ref of component in async v-for

0👍

Instead of doing on this.$refs.myItems during mounted, you can do it after the axios promise returns the the response.

you also update items and loaded, sou if you want to use watch, you can use those

👤Daniel

0👍

A little late, maybe it helps someone.

The problem is, you’re using v-if, which means the element with ref="myItems" doesn’t exist yet. In your code this only happens when Axios resolves i.e. this.loaded.

A better approach would be to use a v-show.

<template>
<div>
    <div v-show="loaded">
        <div ref="myItems">
            <div v-if="loaded">
            <div v-for="item in items">
                <div>{{ item.name }}</div>
            </div>
            </div>
        </div>
    </div>
    <div v-show="!loaded">
        Loading...
    </div>
</div>
</template>

The difference is that an element with v-show will always be rendered and remain in the DOM; v-show only toggles the display CSS property of the element.

https://v2.vuejs.org/v2/guide/conditional.html#v-show

Leave a comment