cal
cal

Reputation: 1873

Accessing element within a component

I'm trying to access the root element a component with this.$children.$el, however, I'm getting undefined in the console. I can see the $el property on the object when I console.log(this.$children), so I'm not quite sure where I'm going wrong, any help would be greatly appreciated.

<template>
    <div>
        <Project
            v-for="project in projects"
            :key="project.sys.id"
            :title="project.fields.title"
            :images="project.fields.images"
        />
    </div>
</template>

<script>
import Project from '~/components/Project'

export default {
    mounted() {    
        const projects = this.$children.$el
    },
    components: {
        Project
    }
}
</script>

Upvotes: 0

Views: 65

Answers (1)

Murat
Murat

Reputation: 1205

As stated in the vue.js documentation this.$children returns an array of children components. You could see your child component by printing this.$children[0] and its root element by priting this.$children[0].$el.

If you have many children components and want to target a specific one, you can tag your component with a ref attribute like below :

<template>
    <div>
        <Project
            v-for="project in projects"
            :key="project.sys.id"
            :title="project.fields.title"
            :images="project.fields.images"
            ref="project"
        />
    </div>
</template>

<script>
import Project from '~/components/Project'

export default {
    mounted() {    
        console.log(this.$refs.project)
    },
    components: {
        Project
    }
}
</script>

Upvotes: 1

Related Questions