Using any JavaScript third party Library in vue.js

Time:2021-6-15

How to introduce JavaScript third party library into vue.js project


global variable


The simplest way to add a third-party JavaScript library to a project is to make it a global variable by attaching it to a window object

//Entry.js file
window._ = require('lodash'); 
Javascript code:
//Mycomponent.vue file
export default {
  created() {
    console.log(_.isEmpty() ? 'Lodash everywhere!' : 'Uh oh..');
  }
}

This situation will make the window variables grow, but most importantly, they can’t use the server to render. When the application is running on the server, the window object is undefined, so an error will be thrown if you try to access the properties under the window.


Import in each file


Another second rate method is to import the library into each file

//Mycomponent.vue file
import _ from 'lodash';
export default {
  created() {
    console.log(_.isEmpty() ? 'Lodash is available here!' : 'Uh oh..');
  }
}

This is effective, but you need to manually import and remove it repeatedly, which is a pain point: you must remember to import the library into each file, and then remember to remove a file from the file when you don’t use the library. If you don’t set up your build tool correctly, you may end up with multiple copies of the same library in the build package.


A better way


The cleanest and most robust way to use JavaScript libraries in Vue projects is to proxy them as properties of Vue prototype objects. In this way, we add the moment date and time library to our project:

Javascript code:
//Entry.js file
import moment from 'moment';
Object.definePrototype(Vue.prototype, '$moment', { value: moment });
Since all components inherit methods on Vue prototype objects, this makes moment automatically available to any component, with no global variables or any components that need to be manually imported. It can be accessed in any instance / component simply through this. $moment

Javascript code:
//Mycomponent.vue file
export default {
  created() {
    console.log('The time is ' . this.$moment().format("HH:mm"));
  }
}

Now let’s take a moment to see how this works.

Object.defineProperty
We usually set an object property like this:

Javascript code:
Vue.prototype.$moment = moment;

You can do this, but by using object. Defineproperty, we can use descriptors to define our properties. Descriptors allow us to set low-level details, such as whether our properties are writable and whether they are displayed during enumeration in the for loop.

We usually don’t use descriptors in our daily use of JavaScript, because 99% of the time we don’t need such detailed attribute allocation. But this gives us an obvious advantage: by default, properties created with descriptors are read-only.

This means that some muddleheaded developers (maybe you) can’t do some stupid things in the component and destroy everything

Javascript code:
this.$http = 'Assign some random thing to the instance method';
this.$http.get('/'); // TypeError: this.$http.get is not a function
On the contrary, our read-only instance can protect our library well, because if someone tries to override it, they will get an error: typeerror: cannot assign to read only property

$


You’ll notice that we proxy the library to a property name prefixed with the dollar sign “$”. You may have seen other properties and methods, for example, $refs, $on, $mount, etc. all start with “$”.

Although it is not necessary to add a prefix to the property name, it can remind confused developers (maybe you). This is a public API property or method, and you are welcome to use it. Unlike instances of other properties, it may only be for Vue’s internal use.

As a prototype based language, there are no (real) classes in JavaScript, so there are no “private” and “public” variables or “static” methods. This Convention is a good substitute, and we think it is worth observing.


this


You’ll also notice that you can use this. Libraryname to use the library, but there’s a small problem because it’s now an instance method.

However, as a result, unlike global variables, you have to make sure you are in the correct scope when using the library. Internal callback methods cannot access your library through this.

Fortunately, the arrow function in ES6 is a good solution to ensure that you are in the right scope:

Javascript code:
// script.js
this.$http.get('/').then(res => {
  if (res.status !== 200) {
    this.$http.get('/') // etc
    //Works only in arrow callback functions. Note: you can also use Es5's bind();
  }
});

Why not make it a plug-in?

If you plan to use JavaScript third-party libraries in multiple Vue projects, or you want to share your libraries with the world, you can build them into plug-ins!

The plug-in extracts the complexity part, allowing you to add the library of your choice by simply doing the following in the project:

Javascript code:
// script.js
import MyLibraryPlugin from 'my-library-plugin';
Vue.use(MyLibraryPlugin);

With these two lines, we can use JavaScript third-party libraries in any component, just as we can use Vue router, vuex and other plug-ins that use Vue. Use.

Write a plug-in
First, create a file for your plug-in. In this example, I’ll create a plug-in to add Axios to all your Vue instances and components, so I’ll call the file Axios. JS.

The main content to understand is that the plug-in must expose an install method and take the Vue constructor as the first parameter

Javascript code:
// axios.js
export default {
  install: function(Vue) {
    // Do stuff
  }
}

Now we can add the library to the prototype object using the method described earlier:

Javascript code:
// axios.js
import axios from 'axios';
export default {
  install: function(Vue,) {
    Object.defineProperty(Vue.prototype, '$http', { value: axios });
  }
}

What we need to do now is add our library to a project with the use instance method. For example, we can now easily add Axios libraries:

Javascript code:
// entry.js
import AxiosPlugin from './axios.js';
Vue.use(AxiosPlugin);
new Vue({
  created() {
    console.log(this.$http ? 'Axios works!' : 'Uh oh..');
  }
})

Egg: plug in optional parameters


The install method in your plug-in allows you to accept optional parameters. Some developers may not like to use the method name $HTTP of Axios instance, because Vue resource already uses this name, so let’s use an optional parameter to make them your preferred method name:

Javascript code:
// axios.js
import axios from 'axios';
export default {
  install: function(Vue, name = '$http') {
    Object.defineProperty(Vue.prototype, name, { value: axios });
  }
}
Javascript code:
// entry.js
import AxiosPlugin from './axios.js';
Vue.use(AxiosPlugin, '$axios');
new Vue({
  created() {
    console.log(this.$axios ? 'Axios works!' : 'Uh oh..');
  }
})