【问题标题】:Vue3: cannot access computed prop from another computed prop when using TypeScriptVue3:使用 TypeScript 时无法从另一个计算道具访问计算道具
【发布时间】:2021-05-09 07:38:53
【问题描述】:

我有一个带有 TypeScript 的 Vue3 项目,我发现我无法从另一个计算属性中的一个计算属性访问返回的 JS 对象的属性(使用点表示法或命名索引)。

因此,鉴于下面的代码,我的 TS 编译器在尝试读取 this.user 对象上的 friends 时会出现编译错误。这是有道理的,因为 this.user 是一个函数,但在 Vue 世界中它被视为一个属性。如果删除lang="ts" 部分,代码将正常工作。

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: String,
  },
  computed: {
    user: function(): { friends: [] } {
      return { friends: [] };
    },
    formattedFriends: function() {
      return this.user.friends.map((f: any) => f);
    },
  },
});
</script>

这是错误:

Failed to compile.

src/components/HelloWorld.vue:92:24
TS2339: Property 'friends' does not exist on type '() => { friends: never[]; }'.
    90 |     },
    91 |     formattedFriends: function() {
  > 92 |       return this.user.friends.map((f: any) => f);
       |                        ^^^^^^^
    93 |     },
    94 |   },
    95 | });

我使用 Vue cli (vue create) 创建了这个示例代码。

我不确定这是否是 TypeScript 或 Vue 的问题?有任何想法吗?我不想删除此代码的 TypeScript 标记,但可能是最好的选择。

【问题讨论】:

    标签: javascript typescript vue.js vuejs3


    【解决方案1】:

    可能不是最好的解决方案,但我想您可以通过指定 this 参数来安抚编译器..

    formattedFriends: function(this: any) { // or a stricter type if you wish
      return this.user.friends.map((f: any) => f);
    },
    

    【讨论】:

      【解决方案2】:

      一种方法是在访问之前转换类型:

      computed: {
          user: function(): { friends: [] } {
              return { friends: [] };
          },
          formattedFriends: function() {
              const typedUser = (this.user as { friends: [] })
              
              return typedUser.friends.map((f: any) => f);
          },
      },
      

      有兴趣知道是否有更好的方法。

      【讨论】:

        【解决方案3】:

        不确定您的用户计算应该做什么,因为它没有反应源?

        然而,在 Vue3 中,使用响应式 API 会更好,并且可以执行类似的操作

        export default defineComponent({
          name: "HelloWorld",
          props: {
            msg: String,
          },
          setup() {
            const user = reactive({friends:[]})
            const formattedFriends = computed(() => user.friends.map((f : any) => f))
            return {
              user,
              formattedFriends
            }
          },
        });
        

        【讨论】:

        • OP 可能只是用一个简单的例子来说明问题。
        猜你喜欢
        • 2019-03-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-17
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        • 2018-09-11
        • 2021-07-09
        相关资源
        最近更新 更多