简体   繁体   English

如何在 vue.js 应用程序中使用 jQuery 脚本?

[英]How to use jQuery script inside vue.js app?

How to use jQuery script inside vue.js app?如何在 vue.js 应用程序中使用 jQuery 脚本?

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:我像这样运行 jQuery 脚本,但是当我将.pickadate类添加到我的输入时它没有反应并且 datepicker 没有出现:

$('.pickadate').pickadate({
    max: Date.now(),
    format: "yyyy-mm-dd"
});

You need to hook into the lifecycle hooks of Vue ( mounted and beforeDestroy ).您需要挂钩 Vue 的生命周期挂钩( mountedbeforeDestroy )。 You can then access the root element of the component with this.$el .然后,您可以使用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 Vue的生命周期钩子见官方文档: https ://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

Similiarly, I need to run customized jQuery extension scripts in Vue component, in order to reuse some very complicated functions (writen in es5).同样,我需要在 Vue 组件中运行自定义的 jQuery 扩展脚本,以重用一些非常复杂的功能(用 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
        ...
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM