在vue中如何使用GraphQL

Egg.js中使用GraphQL-简单实战中咱们在Graphql的服务端,这里咱们讲讲如何在Vue中使用GraphQL。html

1. 初始化vue项目

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
复制代码

2. 安装Apollo客户端

vue-apollo能够帮助你在应用中使用GraphQL的一套工具。npm

你能够使用Apollo Boost或 直接使用 Apollo Client(须要更多配置工做)。json

name这里用Apollo Boost就能够了,若是你想要更细粒度的控制,能够去看Vue Apollo的文档。bash

Apollo Boost 是一种零配置开始使用 Apollo Client 的方式。它包含一些实用的默认值,例如咱们推荐的 InMemoryCacheHttpLink,它很是适合用于快速启动开发。app

将它与 vue-apollographql 一块儿安装:工具

npm install --save vue-apollo graphql apollo-boost
复制代码

3. 建立ApolloClient实例

在你的应用中建立一个 ApolloClient 实例:post

/src/utils/graphql.jsui

import ApolloClient from 'apollo-boost';

const apolloClient = new ApolloClient({
  // 你须要在这里使用绝对路径
  uri: 'http://127.0.0.1:7001/graphql'
})

export default apolloClient;
复制代码

4. 添加GraphQL的操做实例

/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
    })
}
复制代码

5. 调试

/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>
复制代码

效果以下:

相关文章
相关标签/搜索