I get this error message in my console:
ERROR in src/components/Dashboard.vue:20:32 TS2339: Property 'fetchAllProducts' does not exist on type '{ data: () => { products: Product[]; }; mounted(): Promise; methods: { fetchAllProducts(): Promise; }; }'.
18 | }),
19 | async mounted() {
> 20 | const res = await this.fetchAllProducts();
| ^^^^^^^^^^^^^^^^
21 | this.products = res;
22 | console.log(res)
23 | },
ERROR in src/components/Dashboard.vue:21:14 TS2339: Property 'products' does not exist on type '{ data: () => { products: Product[]; }; mounted(): Promise; methods: { fetchAllProducts(): Promise; }; }'.
19 | async mounted() {
20 | const res = await this.fetchAllProducts();
> 21 | this.products = res;
| ^^^^^^^^
22 | console.log(res)
23 | },
24 | methods: {
My code:
<script lang="ts">
import { Product } from '@/types/types';
import axios from 'axios'
export default {
data: () => ({
products: [] as Product[]
}),
async mounted() {
const res = await this.fetchAllProducts();
this.products = res;
console.log(res)
},
methods: {
async fetchAllProducts(){
try {
const res = await axios.get('https://fakestoreapi.com/products')
return res.data;
} catch (e) {
console.log(e)
}
}
}
}
</script>
The code itself works, how to make the TS stop to cry?
CodePudding user response:
If you're using vue 2 you should create your component using Vue.extend
helper :
<script lang="ts">
import { Product } from '@/types/types';
import axios from 'axios'
import Vue from 'vue';
export default Vue.extend({
data: () => ({
products: [] as Product[]
}),
async mounted() {
const res = await this.fetchAllProducts();
this.products = res;
console.log(res)
},
methods: {
async fetchAllProducts(){
try {
const res = await axios.get('https://fakestoreapi.com/products')
return res.data;
} catch (e) {
console.log(e)
}
}
}
})
</script>
for Vue 3 use defineComponent