【问题标题】:Unexpected token when declaring vue component @Prop with typescript使用打字稿声明 vue 组件 @Prop 时出现意外标记
【发布时间】:2020-10-14 02:35:44
【问题描述】:

我正在尝试将 typescript 与 vuejs 一起使用,通常我使用类似的东西

  @Component({
    props: ['uploadUrl'],
  })

  export default class SelectionModal extends Vue {
    let x = this.uploadUrl // This variable `uploadUrl` is NOT resolved in my IDE
  }

但uploadUrl 在我的IDE (phpStorm) 中没有解析

但是我们可以使用vue-property-decorator 来修复它,方法是像记录的here 一样声明@Prop。代码变为:

<template>
// ... 
</template>

<script type="ts">
  import {Component, Vue, Prop} from 'vue-property-decorator';
  
  @Component
  export default class SelectionModal extends Vue {
    @Prop(String) readonly uploadUrl!: string

    let x = this.uploadUrl // This variable `uploadUrl` is RESOLVED in my IDE
  }
</script>

然而,这个基本声明引发了这样的问题

SyntaxError: /myProject/src/path/to/MyComponent.vue: Unexpected token (33:25)

  31 | 
  32 | export default class SelectionModal extends Vue {
> 33 |   @Prop(String) readonly uploadUrl!: string
     |                          ^

这里的任何人都有一个想法:

1-如何使用第一种解决方案并解决uploadUrl

2- 或者如何解决Unexpected token 问题?

【问题讨论】:

  • 你能创建一个打字稿游乐场来复制这个问题吗?我尝试了类似的in this playground, but it works fine already.
  • 另外,不应该是&lt;script lang="ts"&gt;,即lang而不是type吗?我注意到readonly 声明是您显示的代码的第一部分,它不是有效的javascript,所以我的猜测是vue 没有将该脚本转换为js,因为lang 标签不正确。

标签: typescript vuejs2 properties phpstorm vue-property-decorator


【解决方案1】:

您的第一个示例无法编译 - 您不能直接在类主体中声明 let,并且通过 this.prop 访问道具会导致“类型上不存在属性 'prop'...”错误时构建应用程序。

当使用正确的 &lt;script&gt; 标签属性时,第二个代码 sn-p 对我来说效果很好 - 尝试将 type 更改为 lang 以将您的代码视为 Typescript 源:

<script lang="ts">
  import {Component, Vue, Prop} from 'vue-property-decorator';
  
  @Component
  export default class SelectionModal extends Vue {
    @Prop(String) readonly uploadUrl!: string
    
    myMethod(){
      let x = this.uploadUrl 
    }
  }
</script>

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 2017-02-16
    • 1970-01-01
    • 2018-12-20
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多