5
votes

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

2
"logData(id) {" ... does not look like a valid syntax to me?axel.michel
@axel.michel updated methods: {}Modelesq
I assume {{data.log}} is set by something other than Vue?Bert
@Bert yep server rendered by a django template. I just want to append click events via vue. Not sure if possible :\Modelesq

2 Answers

12
votes

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>
-1
votes

Much easier solution =

window.app = new Vue({
   el: "#app",
   methods: {
      myMethod(data) { ... }
   }
}

// jQuery
window.app.myMethod(data);