【问题标题】:Export custom javascript file to a Vue component将自定义 javascript 文件导出到 Vue 组件
【发布时间】:2018-07-11 10:44:08
【问题描述】:

我是 Vue.js 的初学者,所以这个问题可能是重复的或幼稚的。我想调用在 Vue 组件内的自定义 javascript 文件中定义的函数。我做了这样的事情。

custom.js

class API{
    function testCall(){
        alert("test ok");
    }
}

export {API}

App.vue

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
    <testcomponent :on-click="getData">
    </testcomponent>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';
import TestComponent from './components/TestComponent.vue';
import API from './js/custom.js';

export default {
  name: 'app',
  components: {
    HelloWorld,
    TestComponent,
    API
  },
  methods: {
    getData(){
        const apiObj = new API();
        apiObj.testCall();
      }
  }
}
</script>

当我使用npm run build 构建时,出现以下错误。

有什么帮助吗?

【问题讨论】:

    标签: javascript npm vue.js


    【解决方案1】:

    1:要在类中定义methods,不需要函数关键字。

    class API{
        testCall(){
            alert("test ok");
        }
    }
    

    2:由于您正在使用export {API} 进行命名导出,因此您的导入语句应该是

    import {API} from './js/custom.js';
    

    3:components options 用于在本地注册 vue 组件。由于 API 不是 vue 组件,请将其从 components 选项中删除。

    【讨论】:

    • 再澄清一点——我的一些函数使用 axios 进行 AJAX 调用。如何访问 custom.js 中的外部库,如 axios、jQuery?
    • @SouvikGhosh 使用 import 语句导入这些模块。例如使用 axios 导入它使用 import axios from 'axios'
    • 我尝试在我的 custom.js 文件和 App.vue 文件中导入它,但它们都没有工作,我得到了构建错误。也尝试使用 require("axios") 但没有用。
    • 没关系。有用。我只需要从 npm 安装 axios。谢谢!!
    【解决方案2】:

    API 不是 Vue 组件 - 您不应将其包含在 components 分支中。此外,如果这只是一堆实用函数,您可以将它们一个一个导出或作为包含对象导出

    // util.js - individual functions
    export function testCall (call) {};
    export function testUser (user) {};
    
    // Vue app
    import { testCall, testUser } from 'util.js';
    
    
    // util.js - object group
    function testCall (call)
    {
    }
    
    function testUser (user)
    {
    }
    
    export default
    {
      testCall,
      testUser
    }
    
    // Vue app
    import API from 'util.js';
    

    【讨论】:

      猜你喜欢
      • 2021-06-25
      • 2021-06-19
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 2021-11-11
      • 1970-01-01
      相关资源
      最近更新 更多