使用vue.js获取调用元素

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

我想做的事:

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

这是调用元素:

 
Test

我可以将什么传递给函数来获取div元素,还是有另一种方法来实现它?

您可以从事件中获取元素,如下所示:

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

然后:

 
Test

或者(如果你想传递另一个参数):

 
Test

[试玩]

你这样做是错误的。

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

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

您需要为methods创建methods对象

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

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

 
Test

然后:

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