vue中使用GraphQL的实例代码
上篇给大家介绍了Java使用Graphql搭建查询服务详解。这里我们讲讲如何在Vue中使用GraphQL。
1.初始化vue项目
npminstall-g@vue/cli vuecreatevue-apollo-demo
选择默认cli的默认模板就可以了
添加/src/graphql/article.js、/src/utils/graphql.js两个文件。
├──node_modules └──public │├──favicon.ico │└──index.html ├──src │├──assets ││└──home.js │├──components ││└──HelloWorld.js │├──graphql ││├──article.js │├──utils ││├──graphql.js │├──App.vue │└──main.js ├──package.json └──package-lock.json
2.安装Apollo客户端
vue-apollo可以帮助你在应用中使用GraphQL的一套工具。
你可以使用ApolloBoost或直接使用ApolloClient(需要更多配置工作)。
name这里用ApolloBoost就可以了,如果你想要更细粒度的控制,可以去看VueApollo的文档。
ApolloBoost是一种零配置开始使用ApolloClient的方式。它包含一些实用的默认值,例如我们推荐的InMemoryCache和HttpLink,它非常适合用于快速启动开发。
将它与vue-apollo和graphql一起安装:
npminstall--savevue-apollographqlapollo-boost
3.创建ApolloClient实例
在你的应用中创建一个ApolloClient实例:
/src/utils/graphql.js
importApolloClientfrom'apollo-boost';
constapolloClient=newApolloClient({
//你需要在这里使用绝对路径
uri:'http://127.0.0.1:7001/graphql'
})
exportdefaultapolloClient;
4.添加GraphQL的操作实例
/src/utils/article.js
importgqlfrom'graphql-tag'
importapolloClientfrom'../utils/graphql'
exportfunctiongetArticleList(params){
returnapolloClient.query({
query:gql`query($first:ID){
articleList(first:$first){
id
title
content
author{
name
age
}
}
}`,
variables:params
})
}
exportfunctioncreateArticle(params){
returnapolloClient.mutate({
mutation:gql`mutation($title:String,$content:String,$author:AddAuthor){
addArticle(title:$title,content:$content,author:$author){
id
title
content
author{
age
name
}
}
}`,
variables:params
})
}
5.调试
/src/App.vue文章列表
文章名称:{{v.title}}----------------({{v.author.name}})
添加文章
标题:作者名称:
作者年龄:
文章内容: