无法在带有打字稿的vue中使用Mixins

新手上路,请多包涵

我有这样的文件夹结构

--Page
   -group.vue
--Services
  -groupMixin.ts

group.vue脚本

<script lang="ts">
     import { Vue, Component, Mixins } from 'vue-property-decorator'

     import { GroupMixin } from '../../services/groupMixin';
     @Component
     export default class Group extends Mixins(GroupMixin) {
        created () {
          console.log(this.test)
        }
      }
</script>

groupMixin.ts代码

import { Vue } from 'vue-property-decorator'
//creating mixins.
export class GroupMixin extends Vue {
  test: string = 'sss'
}

我在这里面临两个问题。

首先,要导入我使用的 ../../ 的 ts 文件,有没有办法使用 ./ 或 @/。在不使用 lang=“ts” 的情况下,我可以导入这样的 js 文件 @/services/…

其次,无法访问我在 groupmixin.ts 中声明的变量 测试

原文由 Sam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 279
1 个回答

我今天花了很多时间试图弄清楚如何让 Vue mixins 在 TypeScript 项目中工作。显然,教程中提到的使用 mixins 的所有常规方法在 TypeScript 中根本不起作用。这些组件无法访问在其混入中定义的属性,因为显然 Vue 框架的混入代码对 TypeScript 不友好。

最终,我确实找到了一种让 mixins 在 TypeScript 中工作的方法。事实上,工作得很好。我的项目中有多个级别的 mixin 继承,mixins 扩展了其他 mixin,并且它完全按照我的预期工作。秘诀是我必须安装这个第三方包,有人写了这个包来修复 TypeScript 中的 mixins:

https://www.npmjs.com/package/vue-typed-mixins

几句警告(但都不是什么大不了的):

  1. 如果我在 .ts 文件而不是 .vue 文件中定义我的混合,这个插件只对我有用。这对我来说不是问题,因为我的 mixins 只包含代码,没有 html 或 css(而且我想不出这甚至有意义的情况)。

  2. 当你在一个组件上包含一个 mixin 时,确保你以与包网站(上面的 url)上的示例相同的方式进行操作。如果您只是简单地安装包而不重构您的代码以遵循站点上的示例,它将无法工作。

这是一个简单的例子:

 // /src/mixins/MyMixin.ts

import Vue from "vue";

export default Vue.extend({
    data: function () {
        return {
            mixinMessage: "this came from MyMixin!"
        };
    },
    created: function () {
        console.log("MyMixin.created()");
    },
    mounted: function () {
        console.log("MyMixin.mounted()");
    },
    methods: {
        mixinOutput: function (text:string) {
            console.log("mixin says: " + text);
        }
    }
});

然后由以下人员使用:

 // /src/components/MyComponent.vue

<template>
    <div>
        whatever
    </div>
</template>

<style>
    /* whatever */
</style>

<script lang="ts">
    import mixins from "vue-typed-mixins";
    import MyMixin from "../mixins/MyMixin";

    export default mixins(MyMixin).extend({
        created: function () {
            console.log("MyComponent.created()");
        },
        mounted: function () {
            console.log("MyComponent.mounted()");

            this.mixinOutput("hello from MyComponent");
            this.mixinOutput(this.mixinMessage);
        }
    });
</script>

原文由 Joe Irby 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题