首页 > 解决方案 > 无法在带有打字稿的 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 中声明的变量测试

标签: typescriptvue.jsvue-mixin

解决方案


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

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

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

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

  1. 只有当我在 .ts 文件而不是 .vue 文件中定义我的 mixin 时,这个插件才对我有用。这对我来说不是问题,因为我的 mixin 只包含代码,没有 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>

推荐阅读