Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access a vue data from jquery on click event handler

Tags:

jquery

vue.js

I have a vue component as

var app_3 = new Vue({
    el:'#app-3',
    data() {
        return {
            step:1,
            models:''
        }
    }
});

And I am handling a click event using jquery like

$('body').on('click', '.models', function() {
});

I would like to access the vue data models from the jquery event handler. How can I access it?

like image 776
Abdunnasir K P Avatar asked Oct 21 '25 07:10

Abdunnasir K P


2 Answers

I dont know your purpose but you can use app_3.step to get and set vue data.

var app_3 = new Vue({
    el:'#app-3',
    data() {
        return {
            step:1,
            models:''
        }
    }
});

$('body').on('click', '.models', function() {
app_3.step +=1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<body>
<div id="app-3">
  Step : {{step}}
</div>
<button class="models">Models</button>
</body>
like image 107
Niklesh Raut Avatar answered Oct 22 '25 22:10

Niklesh Raut


Don't mangle jQuery and Vue together. For event handling Vue has all the tools necessary.

var app_3 = new Vue({
    el:'#app-3',
    data() {
        return {
            step: 1,
            models:''
        }
    },
    methods: {
      decreaseStep() {
        this.step -= 1
      }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app-3">
  Step : {{step}}
  <button @click="step+=1">+</button>
  <button @click="decreaseStep">-</button>
</div>

These are just two simple examples. You'd go with the +-button code if the task is so trivial, otherwise you'd create a function inside the methods object on your viewmodel.

like image 44
connexo Avatar answered Oct 22 '25 20:10

connexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!