npm install vue-apollo graphql apollo-client apollo-link apollo-link-http apollo-cache-inmemory graphql-tag
目前网上看到的方法主要针对webpack.config.js配置如下代码
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader'
}
根据以上得出如下配置
config.module
.rule('gragql')
.test(/\.(graphql|gql)$/)
.exclude
.add(resolve('/node_modules/'))
.end()
.use("graphql-tag/loader")
.loader("graphql-tag/loader")
其中需要注意的两个点
(1)在eclude.add后需要跟上一个end()
(2)在loader("graphql-tag/loader")前需要use("graphql-tag/loader")
新建graphql.js文件,代码如下
import Vue from "vue";
import { HttpLink } from "apollo-link-http"
import ApolloClient, {FetchPolicy} from "apollo-client"
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from "vue-apollo"
import { message } from 'element-ui';
Vue.use(VueApollo);
const httpLink = new HttpLink({
// You should use an absolute URL here
uri: 'http://opm.pupuvip.com/graphql'
})
const apolloClient = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
connectToDevTools: true
})
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
})
export default apolloProvider.provide();
在man.js中进行如下配置
//引入graphql
import provide from "../common/js/graphql.js"
//注册provide组件
new Vue({
el: "#app",
router,
store,
i18n,
render: (h) => h(App),
provide: provide
});
此时已经可以通过this.$apollo.query或者this.$apollo.mutate进行操作
this.$apollo.query({
query:query_name,
variables: {},
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
通常在graphql中需要进行权限校验等,可以统一对方法进行封装,在上述的graphql文件中加入以下文件
查询代码如下:
//query查询
export async function graphqlQuery(query, variables, fetchPolicy) {
try {
//验证是否登陆
verifyToken();
let options = {
query: query,
variables: variables,
fetchPolicy: fetchPolicy ? fetchPolicy : 'network-only',
context: {
headers: {
Authorization:
}
}
};
const response = await apolloClient.query(options);
if (response.errors) {
errorResponse((response.errors[0]));
}
let queryName = (options.query.definitions[0]).name.value;
return (response.data)[queryName];
} catch (error) {
message.closeLoading();
errorResponse(error);
return null;
}
}
//mutation
export async function uGraphqlMutation(mutation, variables, update ){
try {
verifyToken();
let options = {
mutation: mutation,
variables: JSON.parse(JSON.stringify(variables), omitTypename),
update: update,
context: {
headers: {
Authorization:
}
}
};
let result = await apolloClient.mutate(options)
if (result.errors) {
errorResponse(result.errors[0]);
}
return result;
}
catch (e) {
let result = { errors: e };
errorResponse(result.errors);
return result;
}
}