Is there a way in Typescript and Vue (v2.x) to import a function that references this?
I haven't had luck with mixins, and curious if there's a simple approach here.
For example:
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);
}
});
I'm getting the error:
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
CodePudding user response:
You can try
import { Route } from 'vue-router';
declare module "vue/types/vue" { // extend vue typings
interface Vue {
$route: Route;
}
}
export function getPath(this: Vue): string { // specify `this` context
return this.$route.path;
}
mounted(){
const path = this.getPath();
}
CodePudding user response:
You can use composition api useRoutePath.ts:
import { useRoute } from 'vue-router';
export default useRoutePath () {
const route = userRoute();
const getPath = () => route.path;
return {
getPath,
}
}
It already has types and can be extended any time (like get params id or meta)
