最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vue.js - Import external javascript file and use functions globally in vue app - Stack Overflow

programmeradmin0浏览0评论

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: /

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 ponent 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 ponent.vue files throughout my app.

Actual results:

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

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./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 ponent 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 ponent.vue files throughout my app.

Actual results:

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

Share edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Feb 11, 2019 at 5:47 TheRawPerformerTheRawPerformer 1961 gold badge2 silver badges10 bronze badges 1
  • It looks like some of these errors are reported by eslint (e.g. i is already defined). You should fix them. – Decade Moon Commented Feb 11, 2019 at 6:07
Add a ment  | 

1 Answer 1

Reset to default 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();
发布评论

评论列表(0)

  1. 暂无评论