Problem
I am trying to make a custom plugin in my Nuxt TS app. I tried following the Nuxt TS cookbook, but I seem to get a runtime error stating that my custom made function does not exist. I am relatively new to Nuxt and typescript and was hoping someone could help me explain why my function is not being recognized. The compiler shows no errors and when working on it, ts recognizes the function: when you hover over the function it is correctly typed and recognized
error
TypeError: this.$getAgeGroup is not a function
tsconfig.json
{
"compilerOptions": {
"target": "ES2018",
"module": "ESNext",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"resolveJsonModule": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"baseUrl": ".",
"paths": {
"~/*": [
"./*"
],
"@/*": [
"./*"
]
},
},
"exclude": [
"node_modules",
".nuxt",
"dist"
],
"plugins": [
"~/plugins/ageGroups.ts"
],
}
plugins/ageGroups.ts
import Vue from 'vue'
const ageGroups = [
'zeros',
'teens',
'twenties',
'thirties',
'fourties',
'fifties',
'sixties',
'seventees',
'eigthies',
'nineties',
'hundreds',
'hundred-tens',
'hundred-twenties',
] as const;
function getAgeGroup(val: number = 0) {
if (val < 10) return ageGroups[0];
if (val > 120) return ageGroups[11];
val = Math.floor(val / 10);
return ageGroups[val];
}
declare module 'vue/types/vue' {
interface Vue {
$getAgeGroup(val: number): typeof ageGroups[number],
}
}
Vue.prototype.$getAgeGroup = (val: number = 0) => getAgeGroup(val);
components/ResultOverview.vue
export default Vue.extend({
mounted () {
console.log(this.$getAgeGroup(20));
},
...
Any advice/tips would be much appreciated, thank you!