You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue Composition API中如何在setup()内实现转换数据的computed属性

实现步骤

  1. 先导入computedAPI,Vue2环境从@vue/composition-api导入,Vue3直接从vue导入即可。
  2. 组合式API中不需要用mapGetters映射,直接通过store实例获取对应模块的getter即可。
  3. 将原来的infoFields逻辑改写为组合式API的computed属性。

完整代码示例

import { computed } from '@vue/composition-api' // Vue3替换为 import { computed } from 'vue'

setup() {
  const store = useStore<StoreState>();

  // 获取contacts模块的getContact getter
  const getContact = computed(() => store.getters['contacts/getContact'])

  // 重写infoFields计算属性
  const infoFields = computed(() => {
    return [
      {
        value: getContact.value.customer.firstName,
        label: "Fornavn",
      },
      {
        value: getContact.value.customer.lastName,
        label: "Etternavn",
      },
      // 剩余其余字段按相同规则补充即可
    ]
  })

  // 返回给模板使用
  return {
    infoFields,
    // 其他需要暴露给模板的变量可以继续加在这里
  };
},

模板部分

模板代码不需要做任何修改,和原来的Options API写法完全兼容,可直接使用infoFields进行循环渲染。


补充说明

  • 组合式API中,computed返回的是一个ref对象,在setup内部取值需要加.value后缀,模板中会自动解包,不需要加后缀。
  • 如果需要去掉any类型,可以先定义字段类型约束:
    interface InfoField {
      value: string | number;
      label: string;
    }
    // 定义时指定computed泛型
    const infoFields = computed<InfoField[]>(() => {
      // 原有逻辑
    })
    

内容的提问来源于stack exchange,提问作者Terje Nygård

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 16:48:03