Why a ts-class-based vue-component's static method, which is declared in .vue, can only work in a .vue's script block?

Viewed 1650

Why a ts-class-based vue-component's static method, which is declared in .vue, can only work in a .vue's script block?

steps to reproduce

  1. use vue-cli3 to init a typescript project and add shims-vue.d.ts

declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}


  1. add Comp.vue file in your project as below
// Comp.vue 
<template>
  <div></div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
@Component
export default class Comp extends Vue {
  mounted() {

  }
  created(){

  }
  static notWorkFunc(){
    //anything
  }
}

export function anotherNotWorkFunc(){
  //anything
}
</script>

  1. add test.ts and test.vue in your project with specific code as below

test.vue

<script lang="ts">
import ComP,{anotherNotWorkFun} from "./Comp.vue";
ComP.notWorkFunc()
anotherNotWorkFun()
</script>

enter image description here

test.ts


import ComP,{anotherNotWorkFun} from "./Comp.vue";
ComP.notWorkFunc()
anotherNotWorkFun()


enter image description here

As you can see

in .ts not work

in .vue work

I don't know the reason...

The repo is https://github.com/WilkinWendy/vue-ts-problem.

The democode is in ./src/demo

FYI

1 Answers

I think the typescript class components in .vue files actually get compiled to a Vue options object and that is how they are exported. What we do in our project, is in the .vue file we just have the template and at the bottom we have external reference to a code-behind file. Example:

<!-- Comp.vue -->
<template>
  <div></div>
</template>
<script lang="ts" src="./Comp.ts"></script>
<style lang="scss" src="./Comp.scss"></style>

Then we do the following:

// Comp.ts
import { Component } from "vue-property-decorator";

export const SOME_CONST = "SomeValue";

@Component
export class Comp extends Vue{
  public static method(): boolean {
    return true;
  }
}

export default Comp;

this seems to work for us and actually the performance of VSCode/Vetur/TypeScript is much better this way. In addition, when the UX folks work on the CSS/HTML they don't have to touch the .ts file.

Related