首页 > 解决方案 > 组合 API - Vue 3 - 如何在模板中调用函数以获取返回值

问题描述

在我的模板中,我使用以下代码:

 <template> 
    {{ getScope(scope.row, itemIn.field) }}    
 </template>

在我使用的选项 API 中:

methods: {
    getScope(data, key) {
        const str_spl = key.split(".")
        if(str_spl.length == 2) {
            return data[str_spl[0]][str_spl[1]]
        } else {
            return data[key]
        }
    },
}

现在我想转向组合 API 方法。我创建了以下代码,但无法像使用 Options API 那样将其返回。怎么修?

setup() {

 getScope(data, key) {
     const str_spl = key.split(".")
     if(str_spl.length == 2) {
         return data[str_spl[0]][str_spl[1]]
     } else {
         return data[key]
     }
 }

 return {
   getScope,
 };
}

标签: vue.jsvuejs3vue-composition-api

解决方案


在组合 API 中,您需要将方法声明为函数:

const getScope = (data, key) => {
  const str_spl = key.split(".")
  if(str_spl.length == 2) {
     return data[str_spl[0]][str_spl[1]]
  } else {
     return data[key]
  }
}

或者

function getScope(data, key) { ...

推荐阅读