javascript 使用 vue.js 获取调用元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34258422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:27:32  来源:igfitidea点击:

Get the calling element with vue.js

javascriptjqueryhtmlvue.js

提问by landunder

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.

我想在 vue.js 中获取调用 html 元素以通过 jQuery 修改它。现在我给每个元素提供类名 + 索引,然后通过 jQuery 调用它,但这看起来像一个疯狂的黑客。

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?

我可以向函数传递什么来获取 div 元素,或者还有其他方法来实现这一点吗?

采纳答案by Pantelis Peslis

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]

[演示]

回答by vistajess

Youre doing it the wrong way.

你这样做是错误的。

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

datais the state or storage of data for your app.

data是应用程序数据的状态或存储。

you need to create methodsobject for your methods

你需要methods为你的方法创建对象

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

    },
    methods: {

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

});

回答by ceejayoz

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

您希望v-el能够在其上运行 jQuery。例如:

<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();
    }
}