In daily development, the use of JS third-party libraries or plug-ins is required for agile development or faster meeting business needs.
How to introduce JavaScript third-party libraries in Vue projects
Global variables
The simplest way to add a JavaScript third-party library to your project is to window
make it a global variable by attaching it to the object.
How to introduce:
How to use:
Export Default { created () { console.log () {_.isempty ()? ' Lodash everywhere! ': ' Uh oh. ');} }
This will keep the window
variables growing, but most crucially, they cannot use server rendering. When the application is running on the server, the window
object is undefined
, so attempting to access window
the property under will throw an error.
Use ES6 to import each file
The second-rate approach 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 valid, but you need to repeat the manual import and removal, which is a pain point: you have to remember to import the library into each file, and then when one of your files is not using this library, remember to remove it from this file. If you do not set up your build tool correctly, you may end up with multiple copies of the same library in your build package.
A better way
The cleanest and most robust way to use JavaScript libraries in a Vue project is to delegate them to the properties of the Vue prototype object. In this way, we add the moment date and time library to our project:
Import moment from ' moment '; Object.defineprototype (Vue.prototype, ' $moment ', {value:moment});
Since all components inherit the methods on the Vue prototype object, this will make moment automatically available to any component, with no global variables or any components that need to be imported manually. It can be accessed simply by access in any instance/component this.$moment
:
Export Default { created () { console.log (' The time is '. $moment (). Format ("hh:mm");} }
Done!
How to use JavaScript various plugins gracefully in Vuejs