axios 类型脚本抱怨属性x在类型“{ data:()=>

3df52oht  于 2022-11-23  发布在  iOS
关注(0)|答案(1)|浏览(64)

我在控制台中收到以下错误消息:
源/组件/ Jmeter 板中的错误。版本:20:32 TS 2339:属性“fetchAllProducts "在类型”{ data:()=〉{产品介绍:产品[]; }; mounted():承诺;方法:{ fetchAllProducts():承诺; };}'.

18 |     }),
    19 |     async mounted() {
  > 20 |         const res = await this.fetchAllProducts();
       |                                ^^^^^^^^^^^^^^^^
    21 |         this.products = res;
    22 |         console.log(res)
    23 |     },

源/组件/ Jmeter 板中的错误。版本:21:14 TS 2339:属性“products "在类型”{ data:()=〉{产品介绍:产品[]; }; mounted():承诺;方法:{ fetchAllProducts():承诺; };}'.

19 |     async mounted() {
    20 |         const res = await this.fetchAllProducts();
  > 21 |         this.products = res;
       |              ^^^^^^^^
    22 |         console.log(res)
    23 |     },
    24 |     methods: {

我的代码:

<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>

代码本身起作用,如何让TS停下来哭呢?

jhiyze9q

jhiyze9q1#

如果您使用的是vue 2,则应使用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>

对于Vue 3,使用defineComponent

相关问题