3

I'm using Vue.js (cli 3) to build a mock webbshop to practice. I got a javascript file with all the functions for buttons, the basket and the checkout.

Instead of copying all the code into my own vue app. How can I import the Javascript file without getting errors?

What I've tried:

Adding import into the main.js file in my Vue App.(I read through this explanation but I honestly don't understand fully what's happening)

import webbshop from '@/assets/lib/js/webbshop.js';
Object.defineProperty(Vue.prototype, '$webbshop', { value: webbshop });

found here: https://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

Putting a console.log("Test from my webbshop.js") in the beginning. <- works

I get this error in Chrome:

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at showBasket (webshop.js?709d:146)

I also get 21 errors in terminal of VS Code when saving the document. eg.

error: 'i' is already defined (no-redeclare) at src/assets/lib/js/webbshop.js:105:18:
  103 | 
  104 |         // Loopa genom varor
> 105 |         for (var i = 0; i < basketItems.length; i++) {
      |                  ^
  106 |             // Räkna ut kostnad och lägg till summa
  107 |             var itemCost = parseInt(basketItems[i].artCost);
  108 | 

or

error: 'addToBasket' is defined but never used (no-unused-vars) at src/assets/lib/js/webbshop.js:31:10:
  29 | 
  30 | /* Lägg till i varukorg */
> 31 | function addToBasket(el, id, name, cost, image, notify = false) {
     |          ^
  32 | 
  33 |     // Börja med en vara
  34 |     numOfItems = 1;

When I create a button with onclick="addToBasket([some parameters])" it throws error:

Uncaught ReferenceError: addToBasket is not defined
    at HTMLButtonElement.onclick ((index):16)

I also tried:

At the very end of main.js just to keep working and not getting stuck until I get an answer.

function loadjsfile(filename){
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
}
 
loadjsfile("@/assets/lib/js/webbshop.js")

It doesn't load the file at all. But no errors.

From main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import webbshop from '@/assets/lib/js/webbshop.js';
Object.defineProperty(Vue.prototype, '$webbshop', { value: webbshop });

Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

It doesn't have to be scalable or in other means the best solution. I just want a simple way how to import functions from my other file and have them globally accessible in each component of my Vue project.

I read here and I can't imagine I have to put module.exports on from of each function in my external file. Or do I?

You need to export the testFunction before you can require it.

module.exports = function testFunction() {
  // function code
}

Expectations:

I want to access all the functions in the external js file to use in other component.vue files throughout my app.

Actual results:

The browser reads the external js file but the functions don't work.

1
  • It looks like some of these errors are reported by eslint (e.g. i is already defined). You should fix them. Commented Feb 11, 2019 at 6:07

1 Answer 1

3

to add function(s) globally to vue you need to extended vue and write as plugin
it is pretty easy

link

do it as the fallow:
create file plugin.js

import webbshop from '@/assets/lib/js/webbshop.js';

// MyPlugin its just a name change to whatever meet you needs.
MyPlugin.install = function (Vue, options) {
  Vue.myGlobalMethod = function () {
    webshop.dothis();
  };

  Vue.mySecondGlobalMethod = function (a,b,c) {
    webshop.dothis(a,b,c);
  };
...
}

now import it to the main Vue file.

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import plugin from './plugin'

Vue.config.productionTip = false

Vue.use(plugin)

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

after that vue attach your custom methods to all vue instances.
and you can access it anywhere by simply refer it to a vue inner function.
in markup:

<h1 v-text="mySecondGlobalMethod(1,2,3)"></h1>

in javascript:

 const b = this.myGlobalMethod();
Sign up to request clarification or add additional context in comments.

4 Comments

If I understand you correctly I need to import my webbshop.js file into a plugin and there declare all the functions as methods using: ``` Vue.myGlobalMethod = function () { webshop.dothis(); }; ``` So I'm grabbing all the functions and calling them something new (or same) but as a method to Vue.{newGlobalMethod}. And to invoke it I just as normal in markup? Such as `<button onclick="myGlobalMethod()">Buy</button>?
I've tried all of this now a few times. Even completely replacing my own webshop.js file with a dummy test.js file only containing function myFunction(){console.log('Test')} No of it worked and it actually crashed my app. I copied and pasted all the code that you suggested and also tried from Vuejs.org
Does not work. MyPlugin is not defined in the plugin.js file, so how can you add a "install" function to it?
Yes this code has not been tested properly. The plugin.js file does not export anything and so cannot be imported.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.