无法在 vue 中使用 typescript 中的 Mixins

2023-12-27

我有这样的文件夹结构

--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/...

二、无法访问变量test我在 groupmixin.ts 中声明了这一点。


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

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

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

几句话警告(但这没什么大不了的):

  1. 仅当我在 .ts 文件而不是 .vue 文件中定义 mixins 时,此插件才适用于我。这对我来说不是问题,因为我的 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法在 vue 中使用 typescript 中的 Mixins 的相关文章

随机推荐