简体   繁体   English

导入外部javascript文件并在vue app中全局使用函数

[英]Import external javascript file and use functions globally in vue app

I'm using Vue.js (cli 3) to build a mock webbshop to practice.我正在使用 Vue.js (cli 3) 构建一个模拟 webbshop 来练习。 I got a javascript file with all the functions for buttons, the basket and the checkout.我有一个 javascript 文件,其中包含按钮、购物篮和结帐的所有功能。

Instead of copying all the code into my own vue app.而不是将所有代码复制到我自己的 vue 应用程序中。 How can I import the Javascript file without getting errors?如何导入 Javascript 文件而不会出错?

What I've tried:我试过的:

Adding import into the main.js file in my Vue App.将导入添加到我的 Vue 应用程序的 main.js 文件中。 (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/在这里找到: https ://vuejsdevelopers.com/2017/04/22/vue-js-libraries-plugins/

Putting a console.log("Test from my webbshop.js") in the beginning.在开头放置一个console.log("Test from my webbshop.js") <- works <- 作品

I get this error in Chrome:我在 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.保存文档时,我在 VS Code 的终端中也出现 21 个错误。 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:当我使用onclick="addToBasket([some parameters])"创建一个按钮时,它会引发错误:

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.在 main.js 的最后,只是为了继续工作而不是在我得到答案之前被卡住。

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来自 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.我只想要一种简单的方法来从我的其他文件中导入函数并让它们在我的 Vue 项目的每个组件中全局访问。

I read here and I can't imagine I have to put module.exports on from of each function in my external file.在这里阅读,我无法想象我必须将module.exports放在外部文件中每个函数的 from 上。 Or do I?还是我?

You need to export the testFunction before you can require it.您需要先导出 testFunction,然后才能使用它。

 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.我想访问外部 js 文件中的所有函数,以便在我的应用程序中的其他 component.vue 文件中使用。

Actual results:实际结果:

The browser reads the external js file but the functions don't work.浏览器读取外部js文件但功能不起作用。

to add function(s) globally to vue you need to extended vue and write as plugin要将函数全局添加到vue ,您需要扩展vue并编写为plugin
it is pretty easy这很容易

link关联

do it as the fallow:作为休闲活动:
create file plugin.js创建文件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.现在将其导入到主 Vue 文件中。

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.之后 vue 将您的自定义方法附加到所有 vue 实例。
and you can access it anywhere by simply refer it to a vue inner function.你可以在任何地方访问它,只需将它引用到一个 vue 内部函数。
in markup:在标记中:

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

in javascript:在 JavaScript 中:

 const b = this.myGlobalMethod();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM