首页 > 解决方案 > 如何在 TypeScript Vue 组件中访问全局 mixin 的方法?

问题描述

我正在使用 TypeScript 开发一个 Vue 应用程序。我创建了一个 mixin(如下global.mixin.js所示),并注册了它Vue.mixin()(如下main.ts所示)。

global.mixin.js

import { mathHttp, engHttp } from '@/common/js/http'

export default {
  methods: {
    wechatShare(config) {
      config.imgUrl = config.imgUrl
      mathHttp.get('/wechat/config', {
        url: encodeURIComponent(window.location.href),
      }).then((data) => {
        wx.config({
          debug: false,
          appId: data.appId,
          timestamp: data.timestamp,
          nonceStr: data.noncestr,
          signature: data.signature,
          jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
        })
      })
      wx.ready(() => {
        wx.updateAppMessageShareData(config)
        wx.updateTimelineShareData(config)
      })
    },
  },
}

主要的.ts

我注册了全局mixin Vue.mixin()

import globalMixins from './mixins/global.mixin'

Vue.mixin(globalMixins)

但是当我尝试从 Vue 组件中访问 mixin 方法时,我得到一个错误:

property wechatShare doesn't exist on type Test.vue

测试.vue

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

@Component({ components: { } })
export default class Test extends Vue {

  created() {
    this.setWeChatShare()
  }

  setWeChatShare() {
    this.wechatShare
  }
}
</script>

我怎么解决这个问题?

标签: javascripttypescriptvue.jsvuejs2

解决方案


vue-property-decorator对来自的 mixins使用相同的语义vue-class-component。根据vue-class-component文档中的示例,mixin 采用与组件相同的形式:

源/mixin.ts:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class MyMixin extends Vue {
  wechatShare(config) {
    //...
  }
}

使用Mixinsfrom vue-property-decorator(或mixinsfrom vue-class-component),包装您的自定义 mixin,并使用您的组件扩展它:

src/App.vue:

import { Component, Mixins } from 'vue-property-decorator'
// OR
// import Component, { mixins } from 'vue-class-component'

import MyMixin from './mixin'

@Component
export default class App extends Mixins(MyMixin) {
  mounted() {
    this.wechatShare(/* ... */)
  }
}

推荐阅读