如何在TypeScript Vue组件中访问全局mixin的方法?

时间:2019-12-10 04:50:22

标签: javascript typescript vue.js vuejs2

我正在使用TypeScript开发Vue应用程序。我创建了一个混合(如下面的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)
      })
    },
  },
}

main.ts

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

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

Vue.mixin(globalMixins)

但是当我尝试从Vue组件中访问mixin方法时,出现错误:

  

property wechatShare doesn't exist on type Test.vue

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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

vue-property-decorator使用与vue-class-component中相同的semantics for mixins。根据{{​​1}}文档中的示例,mixin的形式与组件相同:

src / mixin.ts:

vue-class-component

使用import Vue from 'vue' import Component from 'vue-class-component' @Component export default class MyMixin extends Vue { wechatShare(config) { //... } } 中的Mixins(或vue-property-decorator中的mixins),包装您的自定义mixin,并使用您的组件进行扩展:

src / App.vue:

vue-class-component

答案 1 :(得分:0)

对于那些想要全局使用mixin并阻止导入每个组件的用户,这是您可以做的。

src / mixins / mixin.ts

 (
  (python-mode . (
                 (python-shell-interpreter . "~/my_project/venv/bin/python")
                 (flycheck-checker . python-pylint)
                 (flycheck-python-pylint-executable . "~/myproject/venv/bin/python")
                 (flycheck-pylintrc . "~/my_project/.pylintrc")
                  )
   )
  )

在src / main.ts内部

    import { Vue, Component } from 'vue-property-decorator'
    import Colors from "@/values/Colors"
    import Strings from "@/values/Strings";

    @Component
    export default class Values extends Vue {
        public test = 'Hello, hello, hello';
        public colors: {} = Colors.light;
        public strings: {} = Strings.pt
    }

在您的src / shims-tsx.d.ts内部

import Values from "@/values/Values";//my Mixin
Vue.mixin(Values)