在Egg.js中使用GraphQL-简单实战中咱们在Graphql的服务端,这里咱们讲讲如何在Vue中使用GraphQL。html
npm install -g @vue/cli
vue create vue-apollo-demo
复制代码
选择默认cli的默认模板就能够了vue
添加/src/graphql/article.js
、/src/utils/graphql.js
两个文件。node
├── 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
复制代码
vue-apollo能够帮助你在应用中使用GraphQL的一套工具。npm
你能够使用Apollo Boost或 直接使用 Apollo Client(须要更多配置工做)。json
name这里用Apollo Boost就能够了,若是你想要更细粒度的控制,能够去看Vue Apollo的文档。bash
Apollo Boost 是一种零配置开始使用 Apollo Client 的方式。它包含一些实用的默认值,例如咱们推荐的 InMemoryCache
和 HttpLink
,它很是适合用于快速启动开发。app
将它与 vue-apollo
和 graphql
一块儿安装:工具
npm install --save vue-apollo graphql apollo-boost
复制代码
在你的应用中建立一个 ApolloClient
实例:post
/src/utils/graphql.js
ui
import ApolloClient from 'apollo-boost';
const apolloClient = new ApolloClient({
// 你须要在这里使用绝对路径
uri: 'http://127.0.0.1:7001/graphql'
})
export default apolloClient;
复制代码
/src/utils/article.js
import gql from 'graphql-tag'
import apolloClient from '../utils/graphql'
export function getArticleList(params) {
return apolloClient.query({
query: gql`query ($first: ID) {
articleList(first: $first){
id
title
content
author {
name
age
}
}
}`,
variables: params
})
}
export function createArticle(params) {
return apolloClient.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
})
}
复制代码
/src/App.vue
<template>
<div id="app">
<div class="list">
<h1>文章列表</h1>
<ul>
<li v-for="(v, k) of list" :key="k">
文章名称: {{ v.title }}----------------({{ v.author.name }})
</li>
</ul>
</div>
<div class="form">
<h1>添加文章</h1>
标题:<input v-model="formData.title" type="text"><br>
做者名称: <input v-model="formData.author.name" type="text"><br>
做者年龄: <input v-model.number="formData.author.age" type="text"><br>
文章内容: <textarea v-model="formData.content" name="" id="" cols="30" rows="10"></textarea>
<button @click="createArticle">添加</button>
</div>
</div>
</template>
<script>
import { getArticleList, createArticle } from './graphql/article'
export default {
name: 'app',
data() {
return {
list: [],
formData: {
title: '',
content: '',
author: {
name: '',
age: ''
}
}
}
},
mounted() {
this.initData()
},
methods: {
initData() {
getArticleList({first: 0})
.then(res=>{
console.log('request success')
console.log(res.data.articleList.length)
this.list = res.data.articleList
})
.catch(err=>{
console.log(err)
})
},
createArticle() {
createArticle(this.formData)
.then(()=>{
this.initData()
})
.catch(err=>{
console.log(err)
})
}
}
}
</script>
复制代码
效果以下: