简体   繁体   English

为什么在.vue 中声明的基于ts-class 的vue-component 的静态方法只能在.vue 的脚本块中工作?

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

Why a ts-class-based vue-component's static method, which is declared in .vue, can only work in a .vue's script block?为什么在.vue 中声明的基于ts-class 的vue-component 的静态方法只能在.vue 的脚本块中工作?

steps to reproduce重现步骤

  1. use vue-cli3 to init a typescript project and add shims-vue.d.ts使用 vue-cli3 初始化一个 typescript 项目并添加 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文件,如下所示
// 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.tstest.vue

test.vue测试.vue

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

在此处输入图片说明

test.ts测试文件


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


在此处输入图片说明

As you can see如你看到的

in .ts not work.ts 中不起作用

in .vue work.vue工作

I don't know the reason...我不知道原因...

The repo is https://github.com/WilkinWendy/vue-ts-problem .存储库是https://github.com/WilkinWendy/vue-ts-problem

The democode is in ./src/demo演示代码在 ./src/demo

FYI供参考

I think the typescript class components in .vue files actually get compiled to a Vue options object and that is how they are exported.我认为.vue文件中的.vue类组件实际上被编译为 Vue 选项对象,这就是它们的导出方式。 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.我们在项目中.vue是在.vue文件中我们只有模板,在底部我们有对代码隐藏文件的外部引用。 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.这似乎对我们有用,实际上 VSCode/Vetur/TypeScript 这样的性能要好得多。 In addition, when the UX folks work on the CSS/HTML they don't have to touch the .ts file.此外,当 UX 人员处理 CSS/HTML 时,他们不必接触.ts文件。

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

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