How to use vue-apollo gracefully in Vue Project

  apollo, graphql, javascript, node.js, vue.js

First, let’s get familiar with the working mechanism of graphql.

A GraphQL query can contain one or more operation, similar to a RESTful API. An operation can be of two types: Query or modification. Let’s look at an example:

`query {
 client(id: 1) {
 id
 name
 }
 }`

Then the problem arises. We have already used axios or fetch or ajax to interact with data, such as:

getRecommdBook (type) {
 this.axios.get(`/books/web/recommendation-api/recommendation/official?  type=${type}`)
 .then(res => {
 if (res.data) {
 this.recommdBookfun(res.data)
 console.log(this.recommdBook)
 }
 })
 .catch(err => {
 console.log(err)
 })
 },

How to use apollo in a familiar way to make the query easier?

First of all, let’s quote Apollo-vue (Apollo’s non-biological son) in the Vue project. The author is Guillaume Chau(vue’s development team member)

githttps://github.com/Akryum/vue …

npm install --save vue-apollo apollo-client

Js reference

// apollo configuration
 
 import { ApolloClient, createNetworkInterface } from 'apollo-client'
 import VueApollo from 'vue-apollo'

Build client
Multiple interface adapted to different interface can be constructed

const networkInterfaceTask = createNetworkInterface({
 uri: '/api/tasks/graphql',
 transportBatching: true,
 opts: {
 credentials: 'include'
 }
 })
 
 const apolloClientTask = new ApolloClient({
 networkInterface: networkInterfaceTask,
 connectToDevTools: true
 })
 
 const apolloProvider = new VueApollo({
 clients: {
 task: apolloClientTask
 },
 defaultClient: apolloClientTask
 })

Use apollo

Vue.use(VueApollo)

Root directory reference

new Vue({
 el: '#app',
 router,
 axios,
 store,
 apolloProvider,
 template: '<App/>',
 components: { App }
 })

So far, the basic configuration is ok
The following is the actual request
In vue’s components, such as test.vue

Our example is a query with parameters
Firstly, build the variables of the query in the component.

import gql from 'graphql-tag'
 
 const getErSeasons = gql`query erSeasons($classId: Long!  ) {
 erSeasons{
 id
 name
 startTime
 endTime
 classTask(class:$classId){
 id
 classId
 startTime
 endTime
 status
 }
 }
 }`

If you don’t understand, check the tutorial api first.
And then in methods

changeClass (id) {
 this.ClassSeasons = []
 this.Select = id
 console.log(this.$apollo.query)
 this.$apollo.query({
 query: getErSeasons,
 variables: {
 classId: this.Select
 }
 })
 .then(res => {
 this.Parse(res.data.erSeasons)
 console.log(res)
 })
 .catch(err => {
 console.log(err)
 })
 }
 
 This form is a little familiar.  Ha ha ha
 All right.  After that, you can pretend to force happily again.
 This article is only suitable for beginners.
 
 Author: koala reading front-end engineer