javascript - 如何在 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>
我怎么解决这个问题?
解决方案
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) {
//...
}
}
使用Mixins
from vue-property-decorator
(或mixins
from 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(/* ... */)
}
}
推荐阅读
- python - 在 Python 中,为什么 GraphQL 枚举值显示为 null?
- macos - 尝试升级 Conda
- javascript - 如何将复选框绑定到已经存在的复选框?
- scala - Scala - 预期 (String, NotInferedB1) 实际 (String, Double)
- docker - 无法让容器在 k8s 中获取 apparmor 配置文件
- java - 编辑文本未显示在我的设备上,即使没有代码错误
- java - 爪哇 | 将字符串持久化为枚举
- python - 跨多列的最后日期和名称的返回值
- django - django-rest-framework - POST 请求返回“方法 \"GET\" 不允许。”
- apache - Apache Proxy Pass 403 Forbidden