Reputation: 589
How to use jQuery script inside vue.js app?
var app = new Vue({
el: '#app',
data: {
users: [{'my_date': ''}]
}
});
<div id="app">
<input class="form-control pickadate" v-model="user.my_date" placeholder="My Date">
</div>
I run jQuery script like this but when I add .pickadate
class to my input it doesn't react and datepicker doesn't appear:
$('.pickadate').pickadate({
max: Date.now(),
format: "yyyy-mm-dd"
});
Upvotes: 2
Views: 5253
Reputation: 16069
You need to hook into the lifecycle hooks of Vue (mounted
and beforeDestroy
). You can then access the root element of the component with this.$el
. Here is an example:
<template>
<div>
<input class="form-control pickadate" v-model="user.my_date" placeholder="My Date">
</div>
</template>
<script>
export default {
data: {
users: [{'my_date': ''}]
},
mounted() {
$('.pickadate', this.$el).pickadate({
max: Date.now(),
format: "yyyy-mm-dd"
});
},
beforeDestroy() {
// remove pickadate according to its API
}
};
</script>
See the official documentation for Vue's lifecycle hooks: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram
Upvotes: 9
Reputation: 957
Similiarly, I need to run customized jQuery extension scripts in Vue component, in order to reuse some very complicated functions (writen in es5). Searched and experimented a lot, at last the following solution saved me:
mounted () {
const script0 = document.createElement('script')
script0.setAttribute(
'src',
'https://xxx/jquery-2.2.4.min.js'
)
script0.async = true
document.head.appendChild(script0)
const script1 = document.createElement('script')
script1.setAttribute(
'src',
'https://yyy/jquery.kdzzz.js'
)
script1.async = true
document.head.appendChild(script1)
},
methods: {
methodA () {
window.$.extfunctionA() // the extended function is defined in the jquery.kdzzz.js
...
}
}
Upvotes: 0