乐趣区

关于javascript:GraphQL实践篇二

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

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

客户端我的项目目录构造如下:

装置

首先咱们先应用 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 端服务了!????????????

退出移动版