DOM element to corresponding vue.js component

2019-03-09 07:48发布

How can I find the vue.js component corresponding to a DOM element?

If I have

element = document.getElementById(id);

Is there a vue method equivalent to the jQuery $(element)?

9条回答
我只想做你的唯一
2楼-- · 2019-03-09 08:02

Just by this (in your method in "methods"):

element = this.$el;

:)

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-09 08:06

Exactly what Kamil said,

element = this.$el

But make sure you don't have fragment instances.

查看更多
Anthone
4楼-- · 2019-03-09 08:06

Since in Vue 2.0, no solution seems available, a clean solution that I found is to create a vue-id attribute, and also set it on the template. Then on created and beforeDestroy lifecycle these instances are updated on the global object.

Basically:

created: function() {
    this._id = generateUid();
    globalRepo[this._id] = this;
},

beforeDestroy: function() {
    delete globalRepo[this._id]
},

data: function() {
    return {
        vueId: this._id
    }
}
查看更多
Bombasti
5楼-- · 2019-03-09 08:12

If you're starting with a DOM element, check for a __vue__ property on that element. Any Vue View Models (components, VMs created by v-repeat usage) will have this property.

You can use the "Inspect Element" feature in your browsers developer console (at least in Firefox and Chrome) to view the DOM properties.

Hope that helps!

查看更多
劫难
6楼-- · 2019-03-09 08:12

Since v-ref is no longer a directive, but a special attribute, it can also be dynamically defined. This is especially useful in combination with v-for.

For example:

<ul>
    <li v-for="(item, key) in items" v-on:click="play(item,$event)">
        <a v-bind:ref="'key' + item.id" v-bind:href="item.url">
            <!-- content -->
        </a>
    </li>
</ul>

and in Vue component you can use

var recordingModel = new Vue({
  el:'#rec-container',
  data:{
    items:[]
  },

  methods:{
    play:function(key,e){
      // it contains the bound reference
      console.log(this.$refs['item'+key]);
    }
  }
});
查看更多
叼着烟拽天下
7楼-- · 2019-03-09 08:19

The proper way to do with would be to use the v-el directive to give it a reference. Then you can do this.$$[reference].

Update for vue 2

In Vue 2 refs are used for both elements and components: http://vuejs.org/guide/migration.html#v-el-and-v-ref-replaced

查看更多
登录 后发表回答