0

目前我将 Vue 2 与 Typescript 一起使用,但我无法向组件添加选项

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src

@Component<Home>({
  components: {
    HelloWorld,
  },

  middleware: "yyy",
})
export default class Home extends Vue {
  mounted() {
    console.log(this.middleware);
  }
}
</script>

我没有定义!

我发现了 1 个类似的问题,我尝试了但仍然没有结果

扩展组件选项

我的 src\shims-vue.d.ts

declare module "*.vue" {
  import Vue from "vue";
  export default Vue;
}
declare module "vue/types/vue" {
  interface Vue {
    middleware?: string;
  }
}

declare module "vue/types/options" {
  interface ComponentOptions<V extends Vue> {
    middleware?: string;
  }
}
4

1 回答 1

1

您的类型声明缺少导入Vue

// shims-vue.d.ts
import Vue from 'vue' 

declare module "vue/types/options" {
  interface ComponentOptions<V extends Vue> {
    middleware?: string;
  }
}

要从您的组件访问该选项,请使用this.$options.middleware(not this.middleware):

export default class Home extends Vue {
  mounted() {           
    console.log(this.$options.middleware);
  }
}
于 2021-07-04T09:12:46.257 回答