在Vue项目中使用 GraphQL

610 阅读1分钟
  1. 安装必要的依赖项:您需要安装apollo-boostgraphql-tagapollo-link-error包。可以使用npm或yarn进行安装。
npm install apollo-boost graphql-tag apollo-link-error --save
  1. 在Vue项目中封装一个函数抛出供外部模块调用。
import { ApolloClient, from, HttpLink, InMemoryCache } from 'apollo-boost'; // 引入 'apollo-boost' 插件
import { onError } from "apollo-link-error";

// Log any GraphQL errors or network error that occurred
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`, // 使用绝对路径,使用时uri需要替换为你自己的graphql服务
  headers: {
    Authorization: `Bearer ${authToken}`,
    'x-hasura-admin-secret': '******'
  }
})


/**
 * 实例化apolloClient
 */

const apolloClient = new ApolloClient({
  link: from([httpLink, errorLink]),
  cache: new InMemoryCache(),
});

export default apolloClient;
  1. 在需要使用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>