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

Vue3组合式API中emit内调用方法报undefined错误怎么解决

Vue3 Composition API 调用自定义方法报错问题解答

错误根源

  1. Vue3 中setup函数的第二个参数context为Vue框架内置对象,仅暴露attrs、slots、emit、expose四个固定属性,你自行定义的location函数是setup作用域下的局部变量,不属于context的属性,因此调用context.location()必然抛出未定义错误。
  2. 你提到去掉context前缀后仅在emit参数调用时报错,本质是作用域变量命名冲突:你的updateLocation方法形参命名为location,与外层自定义的location函数重名。当你传入location参数触发if分支逻辑时,函数内部作用域会优先匹配形参的location值(通常是坐标对象,不是函数),此时调用location()就会报错,其他无命名冲突的函数中调用自然正常。
  3. 额外隐性问题:如果你的center是用ref定义的响应式变量,location函数返回时直接写center会返回ref实例本身,而非实际的坐标值。

修复方案

修改形参名避免命名冲突,同时直接调用setup作用域下的location函数即可,无需加context前缀:

setup(props, context) { 
  // 形参改名避免和外层location函数冲突
  const updateLocation = (newLocation = null) =>{
    if(newLocation) {
      center.value = newLocation
      // 直接调用外层作用域的location函数
      context.emit('mapChange', location())
    }
  }
  const location = () =>  { 
    return {
      // ref变量需要取value获取实际值
      center: center.value
    }
  }
}

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:00:01