繁体   English   中英

如何使用 vue-typescript 中的 mixin 修复 linter 问题?

[英]How to fix linter issues with mixins in vue-typescript?

情况:


我有一个项目,我正在尝试为其创建 mixin,并且 mixin 中的方法与来自组件和其他方法的数据发生反应。 我从 veture 收到关于我所有组件的错误,指出该方法在组合的 vue 实例中不存在。 代码有效,我可以看到 mixin 正在工作,但我很好奇我应该怎么做才能摆脱我在项目中看到的 linting 错误。 我在 vscode 中看到 Vetur 对代码的抱怨,但是,我也在控制台中看到了对 ts-lint 的抱怨。

问题和期望

是什么导致了这些错误,我该如何修复它们? 对于使用相同代码的组件,它会多次弹出,我认为 mixins 是可重用代码的好主意,但它变得很麻烦。

详细信息和代码

带有 Mixin 的 Vue 组件代码

export default Vue.extend({
  name: 'RecentRequests' as string,
  data() {
    return {
      requests: [] as Request[],
      workflows: [] as Workflow[],
      environment: `${process.env.VUE_WEB_API}`,
      search: '',
    }
  },
  async created() {
    await RequestService.getRequest().then((response) => {
      this.$data.requests = response.Data;
    }).catch((err) => {
      this.$data.requests = null;
      this.$data.topFive = null;
      this.$store.dispatch('updateErrorMessage', {message: `${err}`});
      this.$store.dispatch('updateError');
    });
    await WorkflowService.getWorkflow().then((response) => {
      this.$data.workflows = response.Data;
    }).catch((err) => {
      this.$data.requests = null;
      this.$data.topFive = null;
      this.$store.dispatch('updateErrorMessage', {message: `${err}`});
      this.$store.dispatch('updateError');
    });
  },
  mixins: [globalMixins],
  computed: {
    filteredRequests() {
      let searchTerm = this.search.toLowerCase();
      let topFive: any = this.topFive()
      if(this.search === null || this.search === '') {
        return topFive
      } else {
        return topFive.filter((item: any) => {
            return item.WorkflowDisplayName.toLowerCase().includes(searchTerm);
        });
      }
    }
  },
  methods: {
    topFiveRequests() {
      // combine workflows first before running
      this.combineRequestsAndWorkflows(this.$data.requests, this.$data.workflows);
      // make copy of requests array
      const requestsCopy = this.$data.requests.map((x: Request) => x);
      // sort array by most recent
      const mostRecentRequests = requestsCopy.sort((a: any, b: any) => {
        const dateA: any = new Date(a.timeRequested);
        const dateB: any = new Date(b.timeRequested);
        return dateB - dateA;
      });
      const result = mostRecentRequests.splice(0, 4);
      return result;
    },
  },
})
</script>

Vetur 错误的屏幕截图

屏幕上的错误截图

控制台中 tsLint 错误的屏幕截图

在此处输入图片说明

一世

问题是 Typescript 不够聪明,无法知道 Vue 中的 mixin 到底是什么。 您有 2 个选择:

  1. 由于混入延伸Vue的,在你的组件,而不是Vue.extend可以使用YourMixin.extend 请注意,此解决方案仅适用于单个 mixin。
  2. 如果一个组件中有多个 mixin,您可以检查此依赖项

进一步阅读可以在 论坛上找到。

暂无
暂无

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

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