Vue Composition API中如何在setup()内实现转换数据的computed属性
实现步骤
- 先导入
computedAPI,Vue2环境从@vue/composition-api导入,Vue3直接从vue导入即可。 - 组合式API中不需要用
mapGetters映射,直接通过store实例获取对应模块的getter即可。 - 将原来的
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
相关产品推荐
相关产品推荐

