【问题标题】:How can I access this.$route from within vue-apollo?如何从 vue-apollo 中访问 this.$route?
【发布时间】:2017-12-19 09:21:00
【问题描述】:

我正在使用vue-apollographql-tag 构建一个GraphQL 查询。

如果我硬编码我想要的 ID,它可以工作,但我想将当前路由 ID 作为变量传递给 Vue Apollo。

有效(硬编码 ID):

  apollo: {
    Property: {
      query: PropertyQuery,
      loadingKey: 'loading',
      variables: {
        id: 'my-long-id-example'
      }
    }
  }

但是,我无法做到这一点:

不起作用(尝试访问 this.$route 获取 ID):

  apollo: {
    Property: {
      query: PropertyQuery,
      loadingKey: 'loading',
      variables: {
        id: this.$route.params.id
      }
    }
  }

我得到错误:

未捕获的类型错误:无法读取未定义的属性“参数”

有没有办法做到这一点?

编辑:完整的脚本块,以便更轻松地查看正在发生的事情:

<script>
import gql from 'graphql-tag'

const PropertyQuery = gql`
  query Property($id: ID!) {
    Property(id: $id) {
      id
      slug
      title
      description
      price
      area
      available
      image
      createdAt
      user {
        id
        firstName
        lastName
      }
    }
  }
`

export default {
  name: 'Property',
  data () {
    return {
      title: 'Property',
      property: {}
    }
  },
  apollo: {
    Property: {
      query: PropertyQuery,
      loadingKey: 'loading',
      variables: {
        id: this.$route.params.id // Error here!
      }
    }
  }
}
</script>

【问题讨论】:

  • @VamsiKrishna 感谢您的回复。这是一个位于默认导出上的对象。我已经更新了我的问题以在上下文中显示这一点。

标签: javascript vue.js graphql vue-apollo


【解决方案1】:

阅读 vue-apollo 的 documentation(参见反应参数部分),您可以通过使用 this.propertyName 来使用 vue 反应属性。因此,只需将路由参数初始化为数据属性,然后像这样在你的 apollo 对象中使用它

export default {
  name: 'Property',
  data () {
    return {
      title: 'Property',
      property: {},
      routeParam: this.$route.params.id
    }
  },
  apollo: {
    Property: {
      query: PropertyQuery,
      loadingKey: 'loading',
         // Reactive parameters
      variables() {
        return{
            id: this.routeParam
        }
      }
    }
  }
} 

【讨论】:

  • 是的,这行得通!谢谢你。所以变量变成了一个函数,它返回一个对象,而不是直接成为一个对象本身。谢谢!
  • @MichaelGiovanniPumo 很乐意提供帮助,坦率地说,我阅读了文档并学到了一些新东西,所以也感谢你 :)
【解决方案2】:

虽然接受的答案对于发布者的示例来说是正确的,但如果您使用简单的查询,它会比必要的更复杂。

此时this不是组件实例,所以无法访问this.$route

apollo: {
  Property: gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
}

但是,您可以简单地将其替换为函数,它会按您的预期工作。

apollo: {
  Property () {
    return gql`{object(id: ${this.$route.params.id}){prop1, prop2}}`
  }
}

无需设置额外的道具。

【讨论】:

    【解决方案3】:

    你不能像那样访问“this”对象:

    variables: {
      id: this.$route.params.id // Error here! 
    }
    

    但你可以这样:

    variables () {   
        return {
             id: this.$route.params.id // Works here!  
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 2021-06-02
      • 2019-07-18
      • 2018-12-01
      • 2021-07-06
      • 2021-10-27
      • 2022-12-09
      • 2022-11-28
      • 1970-01-01
      相关资源
      最近更新 更多