【问题标题】:apollo vue query variable not recognizing data from page variableapollo vue 查询变量无法识别来自页面变量的数据
【发布时间】:2020-07-25 06:21:46
【问题描述】:

我有以下阿波罗查询设置。我想动态传递用户名,但 this.username 无法识别。

我的代码:

export default {
  data () {
    return {
      username: ''
    };
  },
  beforeCreate () {
    this.$Auth
      .currentAuthenticatedUser()
      .then((userProfile) => {
        this.username = userProfile.username;
      })
      .catch(() => this.$router.push({ name: 'auth' }));
  },
  apollo: {
    services: {
      query: gql(servicesByUser),
      variables: {
        username: this.username
      },
      update: (data) => {
        console.log('apollo:services', data);
        return data.servicesByUser.items;
      },
    },
  },
};

下面的硬编码设置有效:

variables: {
  username: "user-a"
},

此设置不起作用:

variables: {
  username: this.username
},

错误:

TypeError: Cannot read property 'username' of undefined
    at Module../node_modules/babel-loader/lib/index.js?!./node_modules/@quasar/app/lib/webpack/loader.auto-import.js?

我已经花了几个小时,仍然无法解决问题!我错过了什么吗?非常感谢任何帮助!

【问题讨论】:

    标签: vue.js graphql apollo quasar


    【解决方案1】:

    variables 应该是一个函数,以便定义this,如docs 所示:

    apollo: {
      services: {
        ...
        variables () {
          return {
            username: this.username,
          }
        },
      },
    },
    

    【讨论】:

    • 非常感谢,丹尼尔。在将其发布到此处之前,我也确实对函数调用进行了包装,也许我错过了其他东西。它现在可以工作了,非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多