Typescript和Vue(v2.x(中是否有方法导入引用this
的函数?
我在mixins
方面运气不佳,很好奇这里是否有一个简单的方法。
例如:
getPath.ts
export default getPath(): string {
return this.$route.path; // 'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
}
App.vue
import getPath from "./getPath";
import Vue from "vue";
export default Vue.extend({
mounted(){
const path = getPath().apply(this);
}
});
我得到错误:
"this"隐式具有类型"any",因为它没有类型注释。ts(2683(
您可以尝试
import { Route } from 'vue-router';
declare module "vue/types/vue" { // extend vue typings
interface Vue {
$route: Route;
}
}
// specify `this` context
export function getPath(this: Vue, ...args: any[]): string {
return this.$route.path;
}
mounted(){
const path = this.getPath(1,2,3);
},
methods: {
getPath,
}
您可以使用组合apiuseRoutePath.ts
:
import { useRoute } from 'vue-router';
export default useRoutePath () {
const route = userRoute();
const getPath = () => route.path;
return {
getPath,
}
}
它已经有了类型,可以随时扩展(如获取params-id或meta(