首页 > 解决方案 > 当“@”用于打字稿类组件模板中的事件绑定时,Vetur 未正确读取函数名称

问题描述

在某些情况下,vetur 无法正确读取 vue 类组件函数的名称。例如,对于下面的类组件,vetur 会说找不到“nclick”。

<template>
  <span>
    <v-btn v-if="button"
      @click="onClick(button)">
      {{button.label}}
    </v-btn>
    <v-icon v-else-if="icon"
      @click="onClick(icon)">
    </v-icon>
  </span>
</template>

<script lang="ts">
import { ActionMetadata, ButtonAction, IconAction } from '@cat-squared/meta-cat-ts/metadata/types';
import { Component, Vue, Prop } from 'vue-property-decorator';

type ActionType =
  | IconAction
  | ButtonAction
  | (IconAction & {isActive?: boolean; activates: {rel: string}[] });

@Component({
  name: 'MetaAction',
})
export default class extends Vue {
  private currentMetadata?: ActionMetadata

  @Prop()
  private metadata?: ActionMetadata

  mounted() {
    this.currentMetadata = this.metadata;
  }

  onClick(action?: ActionType) {
    this.$emit('action', action);
  }

  get button(): ButtonAction | undefined {
    return this.currentMetadata?.type === 'button' ? this.currentMetadata : undefined;
  }

  get icon(): IconAction | undefined {
    return this.currentMetadata?.type === 'icon' ? this.currentMetadata : undefined;
  }
}
</script>

有了这个错误,vetur 将允许您使用名称“oonClick”,这将在构建和测试时失败。要回购错误,您需要在 vue 2 中使用基于类的组件,在这种情况下,我还使用了可能需要也可能不需要的 vuetify。

标签: typescriptvue.jsvue-class-componentsvetur

解决方案


我今天能够通过将点击处理程序移动到打开标签的同一行来解决这个问题。在某些情况下也使用“v-on:”解决了这个问题,但上面的示例没有。

这是上面的代码,没有任何错误:

<template>
  <span>
    <v-btn v-if="button" @click="onClick(button)">
      {{button.label}}
    </v-btn>
    <v-icon v-else-if="icon" @click="onClick(icon)">
    </v-icon>
  </span>
</template>

<script lang="ts">
import { ActionMetadata, ButtonAction, IconAction } from '@cat-squared/meta-cat-ts/metadata/types';
import { Component, Vue, Prop } from 'vue-property-decorator';

type ActionType =
  | IconAction
  | ButtonAction
  | (IconAction & {isActive?: boolean; activates: {rel: string}[] });

@Component({
  name: 'MetaAction',
})
export default class extends Vue {
  private currentMetadata?: ActionMetadata

  @Prop()
  private metadata?: ActionMetadata

  mounted() {
    this.currentMetadata = this.metadata;
  }

  onClick(action?: ActionType) {
    this.$emit('action', action);
  }

  get button(): ButtonAction | undefined {
    return this.currentMetadata?.type === 'button' ? this.currentMetadata : undefined;
  }

  get icon(): IconAction | undefined {
    return this.currentMetadata?.type === 'icon' ? this.currentMetadata : undefined;
  }
}
</script>


推荐阅读