How to use the jquery plugin in Vue.js

Source: Internet
Author: User

Original: Http://gambardella.info/2016/09/05/guide-how-to-use-vue-js-with-jquery-plugins

Using Vue is really great, but it can also make you a headache when you try to mix it with jquery plugins.

The problem is that jquery and Vue are completely different things, and Vue is rendered through components and data binding, and jquery is primarily used for simple click Processing and powerful manipulation of the DOM.

I tried to find something to help me solve the problem, but I found that some of the components did not work so well for me, so let me show you how to mix vue with the jquery plugin.

What is the purpose of doing this?

Most of the time you can use jquery and some simple Vue to meet your needs, modals, sliders, and so on, and some Vue components together are fast.

So our goal is to use the powerful jquery plugin to quickly combine with Vue.

We will ...

    • Using Vue's custom directives to build jquery
    • Initialize plug-ins when elements are generated
    • Destroy plugin when element is revoked
    • Send event to notify component
    • Receiving events from components and passing them to a plug-in

Tutorial Time

I chose Fengyuan Chen's cropper because it's a great jquery plugin, and if the time limit is within 60 minutes, you certainly won't be able to rewrite the plugin without using Vue.

demo:https://vue-jquery-cropper-demo.firebaseapp.com/

I will show you from the very beginning, if you have finished please skip this section.

Create a project

#Install VUE-CLI$ NPM install-g vue-CLI#Create a new project using the "Webpack" boilerplate$ vue init webpack vue-Cropper? Project Name"Vue-cropper"? Project description"A vue.js Project"? Author"Christian Gambardella <[email protected]>"? Use ESLint to lint your code?"Yes"? Pick an ESLint preset" Standard"? Setup unit tests with Karma + Mocha?"No"? Setup e2e tests with Nightwatch?"No"$ CD vue-Cropper$ NPM Install

Congratulations on having a Vue project.

installing JQuery and Cropper.js
# install jquery & Cropper$ npm install jquery cropper--save

Configuring Webpack for jquery and Vue custom directives

Add a mapping of jquery and Vue custom directives for the Webpack configuration.

Usually Webpack has introduced the full version of jquery, but it is recommended to introduce it again.

You can see that the Webpack template for Vue has been added to the component's folder. I usually add a lot of other folders like custom directives, mixin and so on. In this example, we have added only custom directives.

This will help us to introduce dependencies without knowing their exact path. This is also useful when you refactor your application. You also don't need to manage relative paths.

Add the highlighted sections below to the build/webpack.base.conf file.

Resolve: {  extensions: [', '. js ', '. Vue '],  '. /node_modules ')],  alias: {    ' src ': path.resolve (__dirname, ' ... /src '),    ' assets ': path.resolve (__dirname, ' ... /src/assets '),    ' components ': Path.resolve (__dirname, '. /src/components '),    ' jquery ': Path.resolve (__dirname, ' ... /node_modules/jquery/src/jquery '),    ' directives ': Path.resolve (__dirname, ' ... /src/directives ')  },

Don't forget to add a comma at the end.

Preparing the Application component

I'm going to start using components because I believe it's easier to understand, beautiful and simple components. If you already know how to use them in your component then you can write the instructions immediately to implement them.

Replace the template portion of the Src/app.vue file

<Template>  <DivID= "App">    <imgV-cropper= "Cropoptions"src= "Https://i.imgur.com/WcvkCxl.png"alt= "JQuery Meme">  </Div></Template>

Replace the script section of the Src/app.vue file

<script>'./directives/cropper 'default  {  directives: {    Cropper  } ,  data () {    return  {      cropoptions: {        0,        false   }}} </script>

Some places that need to be focused

    • We also do not need to handle the initialization of the component when we introduce jquery.
    • Consider the Cropper setting option as the original bound data.
    • Cropper will be rendered when initialized, and then destroyed when it disappears.
    • The name of the component can be used as a label in the template and Mycropper into My-cropper.
    • When it is initialized, we must add the V-my-cropper element in the component's template.

Creating Cropper Components

This is the core of this tutorial. We're going to create a Cropper instruction to handle the DOM operations of low-level code. In this case we want to initialize the cropper.

  Custom directives are used to provide a mechanism to map data and manipulate the behavior of the DOM arbitrarily.

Create Src/directives/cropper.js

Import jquery from ' jquery 'Import' Cropper 'Exportdefault{deep:true, bind () {}, update (options) {//Destroy in case it has been initialized already.JQuery ( This. El). Cropper (' Destroy ')    //Initializing directly after destroying    //didn ' t work. Wrapping it in a setTimeout    //Seems to do the trick.SetTimeout (() ={jQuery ( This. El). Cropper (Options)},0)}, Unbind () {JQuery ( This. El). Cropper (' Destroy ')  }}

The most central part of each Vue custom component is its provision that can be used to bind, update, and unbind the corresponding method.

    • Bind: Fires only once when the element is generated in the document.
    • Update: Triggered when the bind method is triggered and when the binding data changes, in which case cropoptions is just an object. Vue.js the custom directive needs to know if its related property is also an object. That's why we need to add deep:true in this case.
    • Unbind: triggered when the DOM element is removed, the component can be destroyed in this method and the monitored event is removed.

There will be a slight change in Vue 2.

The VM instance is passed as a function parameter and is not set to this.

The Update method of an instruction can only be triggered after the data has changed and not after the bind method.

Run for the first time

This is the minimum we can do, let's run up and see how.

This is done quickly, so we didn't add the Cropper style, let's add and run again.

Add highlighted parts to the Src/main.js file First

Import '.. /node_modules/cropper/dist/cropper.css 'vue'./app '/**/   New  Vue ({  ' body ', components  : {App}})

Start the service

$ npm Run Dev

When everything is done, you should see a picture and a cropbox and can make it move.

Note: The latter part of the translation to be continued

How to use the jquery plugin in Vue.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.