1

GraphQL实践篇之Vue+GraphQL搭建客户端

上一篇我们介绍了使用Nestjs+GraphQL搭建服务端,这篇文章记录使用Vue+GraphQL搭建客户端。

客户端项目目录结构如下:
image

安装

首先我们先使用vue-cli新建项目,接着安装依赖:

npm install apollo-cache-inmemory apollo-client apollo-link apollo-link-http apollo-link-ws apollo-utilities vue-apollo -S

引入依赖

// main.js
import Vue from 'vue'
import App from './App.vue'
import { apolloProvider } from './vue-apollo';

Vue.config.productionTip = false

new Vue({
    render: h => h(App),
    // 像 vue-router 或 vuex 一样注入apolloProvider 
    apolloProvider,
}).$mount('#app')
// vue-apollo.js
// 相关文档请查阅 https://apollo.vuejs.org/zh-cn/
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import Vue from 'vue'
import VueApollo from 'vue-apollo'
// 新的引入文件
import { split } from 'apollo-link'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'

Vue.use(VueApollo)

// 与 API 的 HTTP 连接
const httpLink = createHttpLink({ // 你需要在这里使用绝对路径 
    uri: 'http://localhost:3001/graphql',
})
// 创建订阅的 websocket 连接
const wsLink = new WebSocketLink({
    uri: 'ws://localhost:3001/graphql',
    options: {
        reconnect: true,
    }
})
// 使用分割连接的功能
// 你可以根据发送的操作类型将数据发送到不同的连接
const link = split(({ query }) => {
    const definition = getMainDefinition(query)
    return definition.kind === 'OperationDefinition' && definition.operation === 'subscription'
    },
    wsLink,
    httpLink
)
// 创建 apollo 客户端
const apolloClient = new ApolloClient({
    link,
    cache: new InMemoryCache(),
    connectToDevTools: true,
})

export const apolloProvider = new VueApollo({       
    defaultClient: apolloClient,
})

编写业务代码

// App.vue
<template>
 <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <HelloGraphQL /> </div></template>
<script>
import HelloGraphQL from './components/HelloGraphQL.vue'

export default {
    name: 'app',
    components: {
        HelloGraphQL
    }
}
</script>
<style>
#app {
    font-family: 'Avenir',Helvetica, Arial, sans-serif;     -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale; 
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
}
</style>
// HelloGraphQL.vue
<template>
    <div class="hello">
        作者姓氏:{{author.firstName}}
        <button @click="changeAuthor">修改作者姓氏</button>
        <br> <br> 
        新增标题:{{post.title}}
        <button @click="addPost">添加文章</button>
        <br> 
        订阅成功次数:{{receivedSubscriptionTimes}}
    </div>
</template>
<script>
import gql from 'graphql-tag'
export default {
    name: 'HelloGraphQL',
    data: function (){
        return {
            author: {},
            post: {},
            receivedSubscriptionTimes: 0
        } 
    },
    apollo: {
        // Apollo 的具体选项
        author: gql`query author {
            author(id: 2) {
                id,
                firstName,
                posts {
                    id,
                    title
                }
            }
        }`,
        $subscribe: {
            postAdded: {
                query: gql`subscription postAdded{
                    postAdded {
                        id, 
                        title
                    }
                }`, 
                // 变更之前的结果
                result ({ data }) {
                    // 在这里用之前的结果和新数据组合成新的结果
                    // eslint-disable-next-line         
                    console.log(data)
                    this.receivedSubscriptionTimes += 1                 }
            }
        }
    },
    methods: {
        // 修改作者
        changeAuthor() {
            // 调用 graphql 变更
            this.$apollo.mutate({
                // 查询语句
                mutation: gql`mutation changeAuthor {
                    changeAuthor(id: 3, firstName: "firstName" lastName: "lastName") {
                        id,
                        firstName,
                        lastName
                    }
                }`,
                // 参数
                variables: {
                    firstName: '',
                },
            }).then(res => {
                this.author.firstName = res.data.changeAuthor.firstName;
            }) 
        },
        // 添加文章
        addPost() {
            // 调用 graphql 变更
            this.$apollo.mutate({
                // 查询语句
                mutation: gql`mutation addPost {
                    post: addPost {
                        id,
                        title
                    }
                }`
            }).then(res => {
                this.post = res.data.post;
            })
        }
    }
}
</script>

至此,我们便可以请求server端服务了!🎉🎉🎉


PatWu16
71 声望5 粉丝

仰望星空,脚踏实地


下一篇 »
GraphQL总结