admin管理员组

文章数量:1180453

I want to use a javascript class in may Vue application.

My class looks like:

class className { 
   constructor() { 
       ... 
   }  

   function1() { 
       ... 
   }  

   static funtion2() {
        ... 
   } 
}

I tried to import this class in my application like:

  • import className from './fileName.js';
  • var {className} = require('./fileName.js')

In all cases I receive when I want to call a function of the class (className.function2()): the function is undefined.

I want to use a javascript class in may Vue application.

My class looks like:

class className { 
   constructor() { 
       ... 
   }  

   function1() { 
       ... 
   }  

   static funtion2() {
        ... 
   } 
}

I tried to import this class in my application like:

  • import className from './fileName.js';
  • var {className} = require('./fileName.js')

In all cases I receive when I want to call a function of the class (className.function2()): the function is undefined.

Share Improve this question edited May 7, 2018 at 13:12 Kutas Tomy asked May 7, 2018 at 13:07 Kutas TomyKutas Tomy 3492 gold badges7 silver badges19 bronze badges 8
  • 3 do not forget to export you "class" from the module where it is declared – GibboK Commented May 7, 2018 at 13:09
  • Did you spell require right? – Feathercrown Commented May 7, 2018 at 13:09
  • you said function2 does not work, does function1 work? – kwyntes Commented May 7, 2018 at 13:09
  • do you use webpack or similar? – GibboK Commented May 7, 2018 at 13:10
  • @GibboK - did you mean to export the class where I imported? I'm using from the same module. I'm using webpack. – Kutas Tomy Commented May 7, 2018 at 13:11
 |  Show 3 more comments

3 Answers 3

Reset to default 22

You need to export the class to be able to import/require it

//1. For import syntax
export default class className {...}

//2. For require syntax
class className {}
module.exports.className = className
//or
module.exports = {
    className: className
}

Using import/export, you'd use

export class className {}

and

import {className} from '<file>';

Compare to @baao answer, I add the default keyword for the export.

export default class className {}

and in the component.vue file:

<script>
import className from '<pathToFile>';
...
</script>

本文标签: vuejsImport javascript class in vueJSStack Overflow