[英]Get the calling element with vue.js
我想在vue.js中調用html元素來通過jQuery修改它。 現在我給每個元素提供類名+索引,然后通過jQuery調用它,但這看起來像是一個瘋狂的黑客。
我想做的事:
new Vue({
el: "#app",
data: {
testFunction : function(element) {
$(element).doSomethingWithIt(); //do something with the calling element
}
}
});
這是調用元素:
<div v-on:click="testFunction(???)">Test</div>
我可以將什么傳遞給函數來獲取div元素,還是有另一種方法來實現這個目的?
您可以從事件中獲取元素,如下所示:
new Vue({
el: "#app",
methods: {
testFunction : function(event) {
$(event.target).doSomethingWithIt();
}
}
});
然后:
<div v-on:click="testFunction">Test</div>
或者(如果你想傳遞另一個參數):
<div v-on:click="testFunction($event)">Test</div>
你這樣做是錯誤的。
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。 例如:
<div v-on:click="testFunction" v-el:my-element>Test</div>
然后:
// as noted by @vistajess
// your function should be in the methods object
// not the data object
methods: {
testFunction : function() {
$(this.$els.myElement).doSomethingWithIt();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.