简体   繁体   English

如何在 Vue 组件中使用 Vanilla Javascript Class?

[英]How to use an Vanilla Javascript Class in a Vue Component?

I have a laravel project which globally registers vue in the app.js file.我有一个 laravel 项目,它在app.js文件中全局注册 vue。 Vue works in my project as I have it working in another part of my app. Vue 在我的项目中工作,因为我在我的应用程序的另一部分工作。 What makes this situation unique is I do not have somewhere, like a blade file, to pass my vue component through as a medium to be used.这种情况的独特之处在于我没有像刀片文件这样的地方来传递我的 vue 组件作为要使用的媒介。 I have a vanilla js file and a vue component.我有一个香草 js 文件和一个 vue 组件。 I want to be able to use the methods created in my test.js file inside of my testing.vue file.我希望能够在我的testing.vue文件中使用我的test.js文件中创建的方法。 I am simply trying to pass some data from my js to my vue and then console.log() it out to ensure the data is being passed properly.我只是想将一些数据从我的 js 传递到我的 vue,然后console.log()将其传递出去,以确保数据被正确传递。 I do use npm run dev to compile assets.我确实使用npm run dev来编译资产。 The code is pretty boiler plate at this point since my main objective right now is to just pass the data properly.在这一点上,代码是相当样板,因为我现在的主要目标是正确传递数据。 I did confirm the import path as well and it is correct.我也确认了导入路径,它是正确的。 Not sure why the console.log() is not showing in the browser.不知道为什么console.log()没有显示在浏览器中。 This is my current code:这是我当前的代码:

Test.js测试.js

export class Test {
    testing() {
        console.log('this is a test');
    }
} 

Testing.vue测试.vue

<template>
  <div>

  </div>
</template>

<script>
import {Test} from '../../js/Test';

export default {
  name: 'Testing',
  mounted() {
    console.log(Test.testing());
  }
}
</script>

You must create an instance of the Test class in order to use the method.您必须创建Test class 的实例才能使用该方法。 In your Testing.vue file:在您的Testing.vue文件中:

<template>
  <div>

  </div>
</template>

<script>
  import {Test} from '../../js/Test';

  export default {
    name: 'Testing',
    
    mounted() {
      // IMPORTANT to create instance of a class
      const myTestInstance = new Test();
      
      console.log(myTestInstance.testing());
    }
  }
</script>

The method testing() on class Test is not a static method and thus need object to invoke. class Test上的方法testing()不是 static 方法,因此需要 object 来调用。 Alternately, if you don't want to create object, then you can declare the method as static as shown below:或者,如果您不想创建 object,则可以将方法声明为 static,如下所示:

export class Test {
    static testing() {
        console.log('this is a test');
    }
}

You can then us it like this: Test.testing() .然后你可以像这样使用它: Test.testing()

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

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