VueApolloUsing

285 阅读1分钟

官方文档

1. 安装

自动安装

vue add apollo

(官网提供,不过不知道为啥我好像没有安装成功,基本还是手动npm)

手动安装

full configuration:

npm install --save vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag

2. 使用

  1. 新建 apollo.js

    参考:

    其中 middlewareLink 用来设置 headers ,若不使用则可直接用 httpLink

import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
import {ApolloLink} from 'apollo-link'
import Vue from "vue"


Vue.use(VueApollo);

//设置header,设置Authorization
const middlewareLink = new ApolloLink((operation, forward) => {
    const token = localStorage.getItem('token');
    operation.setContext({
        headers: {
            Authorization: `JWT ${token}` || null
        }
    });
    return forward(operation);
})

const httpLink = new HttpLink({
    uri: 'url'
});

const apolloClient = new ApolloClient({
    link: middlewareLink.concat(httpLink),
    //link: httpLink
    cache: new InMemoryCache(),
    connectToDevTools: true,
});

const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    clients: { default: apolloClient },
});

export default apolloProvider;

  1. main.js 中添加
import apolloProvider from './apollo'
new Vue({
  router,
  apolloProvider,  //添加
  render: h => h(App)
}).$mount('#app');
  1. 若使用单独 graphql 文件,则配置 graph-tag loader (可跳过)

配置文件参考: cli配置-webpack相关

在根目录下创建 vue.config.js 文件:

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。你也可以使用 package.json 中的 vue 字段,但是注意这种写法需要你严格遵照 JSON 的格式来写。

module.exports = {
    // webpack 链接 API,用于生成和修改 webapck 配置
    // https://github.com/mozilla-neutrino/webpack-chain
    chainWebpack: (config) => {
        //graphql
        config.module
            .rule('graphql')
            .test(/(\.gql|\.graphql)$/)
            .use('graphql-tag/loader')
            .loader('graphql-tag/loader')
            .end()
    },
};
  1. 在组件函数中使用

SendDiary.graphql :

mutation createDiary($diaryTitle: String!,$diaryText: String!) {
    createDiary(title:$diaryTitle, content:$diaryText) {
        diary {
            title
            content
        }
    }
}

导入 graphql:

import SendDiary from '../../graphql/diarysend/SendDiary.graphql'

简单使用:

updateoptimisticResponse 暂时没用到)

sendDiary: function () {
                this.$apollo
                    .mutate({
                        mutation:SEND_DIARY,
                        variables: {
                            diaryTitle: this.diaryTitle,
                            diaryText: this.diaryText
                        }
                    })
                    .then(()=>{
                        this.$router.push({path:'/'});
                    	console.log('日记发送成功,跳转到主页');
                    })
                    .catch((error)=>{
                        alert('日记发送失败');
                        console.log('日记发送失败:'+error.message);
                    })
            }