【问题标题】:How to solve Vuejs composition API's Ref() type Error?如何解决 Vuejs 组合 API Ref() 类型错误?
【发布时间】:2020-04-06 04:15:29
【问题描述】:

我正在使用 vue 组合 API 并为每个对象都有一个 value 属性的对象数组使用 ref,似乎打字稿将 ref 的值与每个数组内部的属性值混淆了:

如上图所示,typescript 告诉我们 arr 的类型是一个包含名称和值的对象数组,但是当我使用 ref 时,它检测到错误的类型。即使我像下面那样用作转换,问题也无法解决:

const arr2 = ref(arr as { name: string; value: number }[]);

但是当我将 value 属性更改为 value2 或其他内容时,它将起作用:

更新

这是我今天遇到的另一个问题:

我想知道我应该如何解决这个类型错误?

【问题讨论】:

    标签: typescript vue.js vuejs2 typeerror vue-composition-api


    【解决方案1】:

    很遗憾您使用图像来显示您的代码,因为我必须重新输入一遍。

    是的,很明显在对象中使用“值”作为键会使 Typescript 感到困惑。 你可以通过声明一个interface来绕过它,然后你也可以用它来声明arr2

        interface thing {
            name: string,
            value: number
        };
    
        const arr: thing[] = [
            {name: "x1", value: 1},
            {name: "x2", value: 2}
        ];
    
        const arr2: Ref<thing[]> = ref(arr);
    
        arr2.value.forEach(item => console.log(item.name + ':' + item.value));
    

    但是,绕过它的最佳方法显然是不要在对象中使用“值”作为键。

    【讨论】:

    • 将 composition-api 从 0.5.0 升级到 0.6.7 后,我们应该在右侧使用 Ref&lt;thing[]&gt;,例如:const arr2 = ref(arr) as Ref&lt;thing[]&gt;; github.com/vuejs/composition-api/issues/…
    • const items = ref({ heart: [], lungs: [],});如何正确定义?
    猜你喜欢
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多