首先咱们来熟悉下graphql的工做机制前端
一个GraphQL查询能够包含一个或者多个操做(operation),相似于一个RESTful API。操做(operation)能够使两种类型:查询(Query)或者修改(mutation)。咱们看一个例子:vue
`query { client(id: 1) { id name } }`
那么问题来了,咱们已经用熟了axios或者fetch 再或者ajax来进行数据的交互,如:ios
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,使查询更加简便呢git
首先咱们先在vue项目中引用apollo-vue(apollo非亲生儿子) 做者是Guillaume Chau(vue的开发团队人员)github
git:https://github.com/Akryum/vue...web
npm install --save vue-apollo apollo-client
main.js引用ajax
// apollo配置 import { ApolloClient, createNetworkInterface } from 'apollo-client' import VueApollo from 'vue-apollo'
构建客户端
能够构建多个适应不一样接口npm
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 })
使用apolloaxios
Vue.use(VueApollo)
根目录引用api
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) }) } 这个形式是否是有点熟悉了。哈哈哈 能够了。之后就又能够愉快的装逼了 本文章只适于初学者 做者:考拉阅读前端工程师