1、安装依赖
npm install --save vue-apollo graphql apollo-boost graphql-tag
2、新建graphql.js封装求情文件
// import ApolloClient from 'apollo-boost' //引入apollo-boost插件
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
const httpLink = createHttpLink({
uri: "http://localhost:8080", //配置api调用连接
})
const middlewareLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization:
'token',
},
}) //request拦截器
return forward(operation).map((response) => {
return response
}) //response拦截器,但是此处并不能对错误响应进行拦截
})
const authLink = middlewareLink.concat(httpLink)
const defaultOptions = {
watchQuery: {
fetchPolicy: 'network-only',
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'network-only',
errorPolicy: 'all',
},
}
const apolloClient = new ApolloClient({
link: authLink,
cache: new InMemoryCache(),
connectToDevTools: true,
defaultOptions: defaultOptions,
})
//导出实例
export default apolloClient
3、api中调用函数
//article.js
import apolloClient from './graphql'
import gql from 'graphql-tag'
//query方式的请求
export function questionById(params) {
return apolloClient.query({
query: gql`query ($id: ID) { //这里的$id:ID 是对请求参数的约束,常见的有String,Int,ID
questionById(id: $id) { //后端中定义的方法名称 括号中的是请求参数
id //想要拿到的参数,不传的话接口中就不会返回这个字段了
title //如上
content //如上
userId //如上
}
}`,
variables: params //变量{id: 1},query($id: Id) 中的id就是取的这里的变量
})
}
//mutation方式的请求
export function add(params) {
return apolloClient.mutate({
mutation: gql`mutation($question: addUserInput!) {
add(question:$question)
}`,
variables: params
})
}
4、在组件中使用
export default {
data() {
return {
list: []
}
},
created() {
this.initData()
},
methods: {
initData() {
questionById({id: 126628556787679232})
.then(res=>{
console.info('获取数据=》'+JSON.stringify(res))
this.list = [res.data.questionById]
})
.catch(err=>{
console.log(err)
})
},
add() {
add({question: {title: '哈哈哈', content: '瓦蓝蓝的天空飞老鹰', userId: 1}}).then(res => {
console.info('添加数据=>'+ JSON.stringify(res))
if(res.data.add) {
uni.showToast({title: '添加成功'})
}
})
}
}
}
</script>