Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJs: importing custom js libraries

I have a VueJS project that I started it with vue-cli webpack. I have a javascript library with functions that I need in all components. I wonder where I need to place this folder and how to call the functions from JSLibrary1 in Component1.vue:

-myJSLibrary
    JSLibrary1.js
    JSLibrary2.js

JSLibrary1.js

var A = A || (function() {
    class B {
        function C(){
            return “hello”;
        }   
    }       
    var obj = new B();
    return obj;
}());

Project structure

VueProject
   build
   config
   src
    assets
    components
        Component1.vue
    App.vue
    main.js
   static

Thanks.

like image 383
user2419831 Avatar asked Jan 11 '18 21:01

user2419831


People also ask

How do I import custom js in Vue?

There are two ways to import a JavaScript library to the Vue Component. The first is to import a local JavaScript library. Here, you can import the JavaScript library by using the 'import' keyword inside the script tag of your Vue file. import * as mykey from '../assets/js/mykey.

How do I use JavaScript library in Vue?

If you're planning to use a library across many Vue projects, or you want to share it with the world, you can build this into your own plugin! Vue. use(MyLibraryPlugin); With these two lines, we can use the library in any component just like we can with Vue Router, Vuex, and other plugins that utilize Vue.

Can you use JavaScript in Vue?

Single File Component One of the most powerful features of Vue. js is Components; it helps you extend essential HTML elements, CSS, and JavaScript to encapsulate reusable code.


1 Answers

libraries.js

export const A = () => {
  // your code
}

export const B = () => {
  // your code
}

Component1.vue

<script>
import { A, B } from '~/path/to/libraries.js'
export default {
  data () {
    return {}
  },
  mounted () {
    // execute A when components is rendered
    A()
  }    
</script>
like image 194
tribe Avatar answered Oct 02 '22 02:10

tribe