- 安装必要的依赖项:您需要安装
apollo-boost
、graphql-tag
、apollo-link-error
包。可以使用npm或yarn进行安装。
npm install apollo-boost graphql-tag apollo-link-error --save
- 在Vue项目中封装一个函数抛出供外部模块调用。
import { ApolloClient, from, HttpLink, InMemoryCache } from 'apollo-boost';
import { onError } from "apollo-link-error";
const errorLink = onError(({ graphQLErrors, networkError }) => {
console.log(`graphQLErrors`, graphQLErrors)
console.log(`networkError`, networkError)
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
const authToken = '';
const httpLink = new HttpLink({
uri: `http://graphql.com.cn/v1/graphql`,
headers: {
Authorization: `Bearer ${authToken}`,
'x-hasura-admin-secret': '******'
}
})
const apolloClient = new ApolloClient({
link: from([httpLink, errorLink]),
cache: new InMemoryCache(),
});
export default apolloClient;
- 在需要使用graphql查询的组件中直接引用apolloClient
<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import apolloClient from '@/graphql';
import gql from 'graphql-tag';
const INFO = gql`
query info ($where: info_bool_exp!) {
list: info(where: $where) {
id
name
age
job
}
}
`
const queryInfo = async (id: string) => {
const res = await apolloClient.query({
query: INFO,
fetchPolicy: "no-cache",
variables: {
where: {
id: {
_eq: id
}
}
}
})
const { data } = res;
console.log(`获取的信息 -- `, data);
}
onMounted(() => {
const { id = '' } = route.query;
queryInfo(id);
})
</script>