簡體   English   中英

使用vue.js獲取調用元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM