2

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"
});
1
  • how are you including jquery? Commented Nov 21, 2018 at 15:16

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

Comments

0

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
        ...
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.