当前位置: 首页 > 后端技术 > Node.js

如何在Vue项目中优雅的使用vue-apollo

时间:2023-04-03 23:44:00 Node.js

首先我们来熟悉一下graphql的工作机制。GraphQL查询可以包含一个或多个操作,类似于RESTfulAPI。操作可以有两种类型:查询或突变。我们来看一个例子:`query{client(id:1){idname}}`那么问题来了,我们已经使用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)控制台.log(this.recommdBook)}}).catch(err=>{console.log(err)})},如何以我们熟悉的形式使用apollo,让查询更简单?首先我们先在vue项目中引用apollo-vue(apollo不是亲生儿子)作者是GuillaumeChau(vue开发组成员)git:https://github.com/Akryum/vue...npminstall--savevue-apolloapollo-clientmain.jsreference//apollo配置import{ApolloClient,createNetworkInterface}from'apollo-client'importVueApollofrom'vue-apollo'buildclient可以构建多个适配不同的接口constnetworkInterfaceTask=createNetworkInterface({uri:'/api/tasks/graphql',transportBatching:true,opts:{credentials:'include'}})constapolloClientTask=newApolloClient({networkInterface:networkInterfaceTask,connectToDevTools:true})constapolloProvider=newVueApollo({clients:{task:apolloClientTask},defaultClient:apolloClientTask})使用apolloVue.use(VueApollo)根目录引用newVue({el:'#app',router,axios,store,apolloProvider,template:'',components:{App}})至此,基本配置就ok了,接下来就是在vue中实际请求了组件,比如test.vue,我们的例子是带参数的query。首先,在组件中构造查询的变量。importgqlfrom'graphql-tag'constgetErSeasons=gql`queryerSeasons($classId:Long!){erSeasons{idnamestartTimeendTimeclassTask(class:$classId){idclassIdstartTimeendTime}status}}}`看不懂先看教程api再看changeClass(id){this.ClassSeasons=[]this.Select=idconsole.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)})}这个表格是不是有点眼熟哈哈哈没关系。以后又可以开开心心的装逼了。本文仅适合初学者。作者:考拉阅读前端工程师