Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire vue method from jquery on click event

I'm trying to append a click event to an already existing dom element.

<div class="logMe" data-log-id="{{ data.log }}"></div>
...
<div id="events"></div>

I can't seem to access outside vue methods within my jquery click handler. It will throw logData is not defined.

new Vue({
   el: '#events',
   mounted() {
      $('.logMe').on('click', function() {
           const data = $(this).data('log-id');
           this.logData(data); // throws logData is not defined
      });
   },
   methods: {
      logData(id) {
         console.log(id); // never fires
         ... hit server
      },
   },
});

If anyone knows of a better way to append click events to .html elements that would be great! But how can I bubble up and find my vue methods? Here's a fiddle to illustrate

like image 440
Modelesq Avatar asked Aug 31 '17 21:08

Modelesq


1 Answers

To get your code working you would write it like this:

console.clear()

new Vue({
   el: '#events',
   mounted() {
      $('.logMe').on('click', (evt) => {
        console.log("called")
           const data = $(evt.target).data('logId');
           this.logData(data); 
      });
   },
   methods: {
      logData(id) {
         console.log(id);
      },
   },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://unpkg.com/[email protected]"></script>
<div class="logMe" data-log-id="10">Something</div>
<div id="events"></div>

Note that the code uses an arrow function to define the click handler so that the appropriate this is captured to call the logData method on the Vue. However, doing that means you lose the this you want to get the data from the data property, so instead the example uses evt.target.

There is an alternative approach where you capture the Vue in a variable and call the method directly from your jQuery event.

console.clear()

const app = new Vue({
   el: '#events',
   methods: {
      logData(id) {
         console.log(id); // never fires
      },
   },
});

$('.logMe').on('click', function(){
  app.logData($(this).data("logId"))
});
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="logMe" data-log-id="10">Something</div>
<div id="events"></div>
like image 165
Bert Avatar answered Oct 04 '22 05:10

Bert