[英]How to access global mixin's methods in TypeScript Vue component?
我正在使用 TypeScript 開發 Vue 應用程序。 我創建了一個 mixin(顯示在下面的global.mixin.js
中),並將它注冊到Vue.mixin()
(顯示在下面的main.ts
中)。
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)
})
},
},
}
我用Vue.mixin()
注冊了全局 mixin:
import globalMixins from './mixins/global.mixin'
Vue.mixin(globalMixins)
但是當我嘗試從 Vue 組件中訪問 mixin 方法時,出現錯誤:
property wechatShare doesn't exist on type 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>
我怎么解決這個問題?
vue-property-decorator
對來自vue-class-component
mixin使用相同的語義。 根據vue-class-component
文檔中的示例,mixin 采用與組件相同的形式:
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class MyMixin extends Vue {
wechatShare(config) {
//...
}
}
使用Mixins
從vue-property-decorator
(或mixins
來自vue-class-component
),包住您的自定義的mixin,並與您的組件擴展它:
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(/* ... */)
}
}
對於那些想要全局使用 mixin 並防止在每個組件中導入的人來說,這就是你可以做的。
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
}
import Values from "@/values/Values";//my Mixin
Vue.mixin(Values)
// add the variables,functions ... inside the vue interface and then you will good to use them anywhere.
interface Vue {
colors,
strings
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.