vue.js

2015-12-14 18 views
7

के साथ कॉलिंग तत्व प्राप्त करें मैं jQuery के माध्यम से इसे संशोधित करने के लिए vue.js में कॉलिंग HTML तत्व प्राप्त करना चाहता हूं। अभी के लिए मैं प्रत्येक तत्व को क्लास नाम + इंडेक्स देता हूं और बाद में jQuery के माध्यम से इसे कॉल करता हूं, लेकिन यह एक पागल हैक जैसा दिखता है।vue.js

मैं आपकी क्या अपेक्षाएं हैं:

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

यह बुला तत्व है:

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

क्या मैं समारोह में पारित div तत्व प्राप्त करने के लिए कर सकते हैं या कोई और तरीका प्राप्त करने के लिए है इस?

उत्तर

6

आप इस तरह की घटना से तत्व मिल सकता है:

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> 

[demo]

+1

क्या होगा यदि आप एक और तत्व के अंदर है? यदि आप उस पर क्लिक करते हैं तो लक्ष्य बच्चे तत्व का संदर्भ देगा। –

0

आप इसे गलत तरीके से कर रहे हैं।

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

data आपके ऐप के लिए डेटा का राज्य या संग्रहण है।

आप अपने तरीकों

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

    }, 
    methods: { 

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

}); 
0

आप v-el उस पर jQuery चलाने के लिए सक्षम होना चाहता हूँ के लिए methods वस्तु बनाने के लिए की जरूरत है।

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