I have just started using vue3 with typescript, I am coming from vue2 with js and i can't understand how to fix an IDE error (the code itself works, but probably is not 100% correct)
so, this is the code
export default {
name: 'Sidebar',
data() {
return {
menu: { name: 'Menu', icon: MenuIcon },
navigation: [
{ id: 0, name: 'Home', icon: HomeIcon, path: '/', count:0, current: true },
{ id: 1, name: 'Users', icon: UsersIcon, path: '/about', count: 3, current: false },
]
}
},
methods: {
makeCurrent: function(item: navItem) {
this.navigation.forEach((nav: { current: boolean; id: any; }) => {
nav.current = nav.id === item.id;
})
}
}
}
the IDE highlights "navigation" in this.navigation.forEach(...
and gives the following error
TS2339: Property 'navigation' does not exist on type '{ makeCurrent: (item: navItem) => void; }'
CodePudding user response:
The best way to the TS inference in a .vue component is to wrap the
export default { ...options }
In the defineComponent
method
So something like this:
import { defineComponent } from "vue";
export default defineComponent({
name: 'Sidebar',
data() {
return {
menu: { name: 'Menu', icon: MenuIcon },
navigation: [
{ id: 0, name: 'Home', icon: HomeIcon, path: '/', count:0, current: true },
{ id: 1, name: 'Users', icon: UsersIcon, path: '/about', count: 3, current: false },
]
}
},
methods: {
makeCurrent: function(item: navItem) {
this.navigation.forEach((nav: { current: boolean; id: any; }) => {
nav.current = nav.id === item.id;
})
}
}
});
PS
You can also use the defineComponent
method in vue.js 2 using the
https://github.com/vuejs/composition-api plugin