kerby
kerby

Reputation: 201

Access to component by DOM element

Component's template:

<template id='someComponentTemplate'>
  <div id="{{ item.id }}">
    <span>{{ item.title }}</span>
  </div>
</template>

List stuff:

<someComponent v-for="item in items" :item=item></someComponent>

Getting component's element by id

var element=document.getElementById('id123');

Now I want to get access to exact component object which handles found DOM element. Is it possible?

Upvotes: 3

Views: 2352

Answers (2)

dadykhoff
dadykhoff

Reputation: 433

A better way to do this is to use Vue references

In your parent page/component do this:

<someComponent ref="id123" v-for="item in items" :item=item></someComponent>

Then you can access it in your component methods like so:

this.$refs.id123

This returns a reference to the SomeComponent component.

Upvotes: 1

kerby
kerby

Reputation: 201

In case somebody will need a solution, here it is:

First, you should wrap component's template body into extra tag (like span or div) for example:

<template id='someComponentTemplate'>
  <div>
    <div id="{{ item.id }}">
      <span>{{ item.title }}</span>
    </div>
  </div>
</template>

and then access component object this way:

var element=document.getElementById('id123');
var component=element.parentElement.__vue__;

Upvotes: 5

Related Questions