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. 使用
-
新建
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;
- 在
main.js中添加
import apolloProvider from './apollo'
new Vue({
router,
apolloProvider, //添加
render: h => h(App)
}).$mount('#app');
- 若使用单独
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()
},
};
- 在组件函数中使用
SendDiary.graphql :
mutation createDiary($diaryTitle: String!,$diaryText: String!) {
createDiary(title:$diaryTitle, content:$diaryText) {
diary {
title
content
}
}
}
导入 graphql:
import SendDiary from '../../graphql/diarysend/SendDiary.graphql'
简单使用:
( update 和 optimisticResponse 暂时没用到)
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);
})
}