admin管理员组

文章数量:1426108

Is there any way to append vue.js events to existing html elements?

HTML elements:

<div class="borrow-button">Borrow</div>
<div class="borrow-button">Borrow</div>
<div class="borrow-button">Borrow</div>

Can I somehow add vue.js event to this divs?

$('.borrow-button').each(function(i, obj) {
    //how to append for example onclick event to this divs? (onclick="borrow")
});

Is there any way to append vue.js events to existing html elements?

HTML elements:

<div class="borrow-button">Borrow</div>
<div class="borrow-button">Borrow</div>
<div class="borrow-button">Borrow</div>

Can I somehow add vue.js event to this divs?

$('.borrow-button').each(function(i, obj) {
    //how to append for example onclick event to this divs? (onclick="borrow")
});
Share Improve this question edited May 6, 2022 at 2:19 Hugo Trentesaux 1,9991 gold badge18 silver badges34 bronze badges asked Dec 16, 2016 at 11:27 Michał LipaMichał Lipa 9882 gold badges12 silver badges22 bronze badges 3
  • Can you elaborate what are you trying to achieve? – Saurabh Commented Dec 16, 2016 at 11:29
  • @saurabh Im using jsgrid to generate table with data, so html elements are already created. When I create in jsgrid div with vue.js event, it doesn't work, so my idea was to append event to this created divs. – Michał Lipa Commented Dec 16, 2016 at 11:49
  • You can't add vue events to HTML vue does not pile. You can add regular js events with jquery or plain js – vbranden Commented Dec 17, 2016 at 17:41
Add a ment  | 

3 Answers 3

Reset to default 3

I am currently not aware of any vue way of doing this. But as jsgrid uses jquery, you can use event handler attachment of it to bind vue methods.

Here is an exmple:

var demo = new Vue({
    el: '#demo',
    data: function(){
        return {
      };
    },
    methods:{
      myMethod () {
        alert('Do whatever you wanns do')
      }
    },
    mounted () {
        $("#myBtn").on('click', this.myMethod);
    }
})

You can check this code working here.

If vue instance is called vm you can use a method inside it to fire the event like this

// Vue Instance
var vm = new Vue({
  methods: {
      handleButton: function(i, obj) {
        //Do whatever you want
      }
  }
})

$('.borrow-button').each(function(i, obj) {
    vm.handleButton(i, obj)
});

VueJS does not provide you this possibility as the purpose is different.

You would need to use Vanilla JS inside the Vue.

本文标签: javascriptHow to append vuejs event to existing html elementStack Overflow