Reputation: 117
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?
Upvotes: 4
Views: 4019
Reputation: 21
On Vue Js i create a method and called it in before Mount:
var app_3 = new Vue({
el:'#app-3',
data() {
return {
step:1,
models:''
}
},
methods: {
// called by beforeMount()
foo() {
let proxy = this
$('body').on('click', '.models', function() {
// call a method
proxy.bar()
// set a variable data
proxy.step = 2
});
},
// called each .model click
bar(){
console.log('it id working');
}
},
beforeMount() {
this.foo()
}
})
Upvotes: 1
Reputation: 56754
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.
Upvotes: 1
Reputation: 34914
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>
Upvotes: 4