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

Vue.js 2中mounted调用方法报错及后续.then函数问题求助

问题解决:Vue.js 2 + Apollo 查询方法调用错误修复

原代码核心错误点

  • 方法定义属性名错误:把methods写成method,Vue无法识别该方法,触发this.getFormula is not a function错误。
  • 箭头函数的this绑定问题:用箭头函数定义getFormula,箭头函数的this不指向Vue组件实例,后续this.formula无法正确赋值。
  • Apollo查询写法错误:直接返回查询配置对象并链式调用.then,普通对象没有then方法,触发then is not a function错误。正确方式是调用this.$apollo.query()执行查询,该方法返回Promise才能链式处理。
  • 查询变量不匹配:查询定义的变量是$id,但查询内部用了$formula_id,参数名不对应会导致查询失败。
  • 变量传递逻辑问题:variables格式错误,且myBeforeArray未通过this访问组件实例属性,可能导致变量无法正确传递。

修正后的完整代码

<script>
import gql from 'graphql-tag'

export default {
  data() {
    return {
      tipoLiquidacion_id: null,
      grupoId: null,
      tipoSeccionLiquidacion_id: null,
      formula: null,
      myBeforeArray: {} // 确保该变量在data中定义或有正确赋值逻辑
    }
  },
  mounted() {
    if (this.$route.params.id_tipo_liquidacion) {
      this.tipoLiquidacion_id = this.$route.params.id_tipo_liquidacion;
      this.grupoId = Number(this.$route.params.id_agrupacion);
    }
    if (this.$route.params.id_tipo_seccion_liquidacion) {
      this.tipoSeccionLiquidacion_id = this.$route.params.id_tipo_seccion_liquidacion;
      this.grupoId = Number(this.$route.params.id_agrupacion);
    }

    this.getFormula()
  },
  methods: { // 修正为methods
    async getFormula() { // 用普通函数保证this指向组件实例,async/await简化Promise处理
      try {
        const response = await this.$apollo.query({
          fetchPolicy: 'cache-and-network',
          query: gql`query formulas($id: ID!){
            formula(id: $id){ // 修正变量名,与定义的$id对应
              myDBdata
            }
          }`,
          variables: {
            id: parseInt(this.myBeforeArray.id) // 通过this访问组件内的myBeforeArray
          }
        })
        this.formula = response.data.formula // 注意取response.data下的formula层级
        console.log(this.formula)
      } catch (error) {
        console.log('Error-> ');
        console.log(error);
      }
    }
  }
}
</script>

可选写法(不用async/await)

如果习惯Promise链式写法,可替换getFormula为:

getFormula() {
  this.$apollo.query({
    // 配置项同上
  }).then(response => {
    this.formula = response.data.formula
    console.log(this.formula)
  }).catch(error => {
    console.log('Error-> ');
    console.log(error);
  })
}

额外注意事项

  • 确保myBeforeArray已被正确赋值,否则parseInt(this.myBeforeArray.id)可能得到NaN,导致查询失败。
  • 确认Apollo客户端已在Vue项目中正确配置,保证this.$apollo可正常访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 23:47:22