最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the calling element with vue.js - Stack Overflow

programmeradmin4浏览0评论

I want to get the calling html element in vue.js to modify it via jQuery. For now I give every element the class name + the index and call it via jQuery afterwards, but this looks like a crazy hack.

What I want to do:

new Vue({
    el: "#app",
    data: {  
        testFunction : function(element) {
            $(element).doSomethingWithIt(); //do something with the calling element
        }
    }
});

This is the calling element:

<div v-on:click="testFunction(???)">Test</div> 

What can I pass into the function to get the div-element or is there another way to achieve this?

I want to get the calling html element in vue.js to modify it via jQuery. For now I give every element the class name + the index and call it via jQuery afterwards, but this looks like a crazy hack.

What I want to do:

new Vue({
    el: "#app",
    data: {  
        testFunction : function(element) {
            $(element).doSomethingWithIt(); //do something with the calling element
        }
    }
});

This is the calling element:

<div v-on:click="testFunction(???)">Test</div> 

What can I pass into the function to get the div-element or is there another way to achieve this?

Share Improve this question asked Dec 14, 2015 at 1:15 landunderlandunder 3821 gold badge5 silver badges18 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

You could get the element from the event like this:

new Vue({
    el: "#app",
    methods: {  
        testFunction : function(event) {
            $(event.target).doSomethingWithIt();
        }
    }
});

And then:

<div v-on:click="testFunction">Test</div>

Or (if you want to pass another parameter):

<div v-on:click="testFunction($event)">Test</div>

[demo]

Youre doing it the wrong way.

new Vue({
    el: "#app",
    data: {  
        testFunction : function(element) {
            $(element).doSomethingWithIt(); //do something with the calling element
        }
    }
});

data is the state or storage of data for your app.

you need to create methods object for your methods

new Vue({
    el: "#app",
    data: {  

    },
    methods: {

    testFunction : function(element) {
            $(element).doSomethingWithIt(); //do something with the calling element
        }
    }

});

You want v-el to be able to run jQuery on it. For example:

<div v-on:click="testFunction" v-el:my-element>Test</div>

then:

// as noted by @vistajess
// your function should be in the methods object
// not the data object
methods: {
    testFunction : function() {
        $(this.$els.myElement).doSomethingWithIt();
    }
}
发布评论

评论列表(0)

  1. 暂无评论