如何在Vue Project中使用vue-apollo

来源:互联网 发布:软件架构怎么做 编辑:程序博客网 时间:2024/06/06 08:56

首先我们来熟悉下graphql的工作机制

一个GraphQL查询可以包含一个或者多个操作(operation),类似于一个RESTful API。操作(operation)可以使两种类型:查询(Query)或者修改(mutation)。我们看一个例子:

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

那么问题来了,我们已经用熟了axios或者fetch 再或者ajax来进行数据的交互,如:

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)        })    },

怎样以我们熟悉的形式来运用apollo,使查询更加简便呢

首先我们先在vue项目中引用apollo-vue(apollo非亲生儿子) 作者是Guillaume Chau(vue的开发团队人员)

git:https://github.com/Akryum/vue...

npm install --save vue-apollo apollo-client

main.js引用

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

构建客户端
可以构建多个适应不同接口

    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    })

使用apollo

Vue.use(VueApollo)

根目录引用

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

好到此为止,基础配置就已经ok了
接下来就是实际的请求了
在vue 的组件中,比如 test.vue

我们的例子是带参数的查询
首先在组件里构建查询的变量

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                              }                            }                          }`

不懂的话先去查下教程api
然后在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)        })    }    这个形式是不是有点熟悉了。哈哈哈可以了。以后就又可以愉快的装逼了本文章只适于初学者作者:考拉阅读前端工程师