typescript - 类型 'x' 上不存在属性 '{toggle():void}'

标签 typescript vue.js nuxt.js nuxt-edge nuxt-bridge

我对 typescript 还很陌生。现在,我已经设置了 nuxt(bridge with typescript) 应用程序并创建了一个名为 menuIcon 的组件;

  <div class="container">


    <div class="menu-icon" :class="active ? 'change' : ''" @click="toggle">
      <div class="bar1"></div>
      <div class="bar2"></div>
      <div class="bar3"></div>
    </div>
    <div
      class="overlay"
      :class="active ? 'overlay-slide-right' : 'overlay-slide-left'"
      @click="toggle"
      id="overlay"
    >
    <!-- html contents here -->
    </div>
  </div>
</template>

<script lang="ts">


export default {
  data(){
    const active:boolean=false;
    return{
        active
    }
  },
  methods: {
    toggle():void{
       this.active= !this.active
    },
  },
};
</script>
<style scoped>
/*css contents here*/
}
</style>

它正在浏览器中运行,但我在终端中看到以下错误。

TS2339: Property 'active' does not exist on type '{ toggle(): void; }'.
    41 |   methods: {
    42 |     toggle():void{
  > 43 |        this.active= !this.active
       |             ^^^^^^
    44 |     },
    45 |   },
    46 | };

ERROR in components/MenuIcon.vue:43:27
TS2339: Property 'active' does not exist on type '{ toggle(): void; }'.
    41 |   methods: {
    42 |     toggle():void{
  > 43 |        this.active= !this.active
       |                           ^^^^^^
    44 |     },
    45 |   },
    46 | };

显然这是关于打字的问题,但我不知道如何解决它。我非常感谢任何人能够向我阐明这些问题。提前致谢。

最佳答案

组件定义需要是 declared with Vue's defineComponent to enable TypeScript support 。 Nuxt Bridge 建议使用 #app 导入中的 defineComponent,尽管您也可以从 @vue/composition-api 导入它。最好使用 #app 别名,因为它包含来自 @nuxtjs/composition-api 的 Nuxt 特定类型。

示例:

<script lang="ts">
import { defineComponent } from '#app';
                      👇
export default defineComponent({
  data() {
    const active:boolean = false;
    return {
      active
    }
  },
  methods: {
    toggle(): void {
      this.active = !this.active
    },
  },
});
</script>

#app 别名通常在 .nuxt/tsconfig.json 中设置,但我发现有必要在根应用程序的 tsconfig 中重新声明它.json 在 VS Code 中工作:

{
  "extends": "./.nuxt/tsconfig.json",
  "compilerOptions": {
    "paths": {
      ⋮
      "#app": [
        "node_modules/@nuxt/bridge/dist/runtime/index"
      ],
    }
  }
}

demo

关于typescript - 类型 'x' 上不存在属性 '{toggle():void}',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69716539/

相关文章:

angular - 如何在 typescript/Angular 中设置 html 元素的样式

asp.net-mvc - 如何在带有 typescript 和 ASP.Net Core 的几个 html 页面中使用 vuejs 2

javascript - Angular 6 AngularFireAuth 检查用户是否在页面呈现之前登录

javascript - 在 Vue.js 中路由器链接的 ":to"属性中传递 props

vue.js - `nuxt.js` vue3的替代品?

javascript - 为什么 ngOnChange 没有检测到 @Input 元素更改而 ngOnDetect 能够这样做

vue.js - Vue 如何从 async/await 函数返回值?

vue.js - 使用 i18n 和 Nuxt 时设置语言属性?

node.js - 遇到错误找不到服务器上的npm和node./usr/bin/env : node: No such file or directory

javascript - 如何在短按按钮或直到功能完成后禁用按钮