vue使用 graphql 进行数据访问全流程

149 阅读1分钟

vue使用 graphql 进行数据访问全流程**

  1. 下载依赖 npm install @apollo/client @vue/apollo-composable graphql graphql-tag --save
  2. 然后,创建一个 ApolloClient 的实例:配置的javascript
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'
import { setContext } from "@apollo/client/link/context";

const httpLink = createHttpLink({
  uri: "http://localhost:8080/graphql", //你的GraphQL服务端接口地址
});

const authLink = setContext((_, { headers }) => {
  const token = "linlin-authentication"; //根据你的应用需求,你可能需要在这里使用你自己的token

  return {
    headers: {
      ...headers,
      authorization: token ? Bearer ${token} : "",
    },
  };
});

const cache = new InMemoryCache();

export const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
 cache,
});
  1. 然后在你的 main.ts 文件中,你需要提供 DefaultApolloClient:
import { createApp, h, provide } from "vue";
import App from "./App.vue";
import { DefaultApolloClient } from "@vue/apollo-composable";
import { apolloClient } from "./apolloClient";

createApp({
  setup() {
    provide(DefaultApolloClient, apolloClient);
  },
  render: () => h(App),
}).mount("#app");‘

最后 在你的 Vue.component 使用这个 ApolloClient 来查询数据:

import { useQuery } from '@vue/apollo-composable';
import gql from 'graphql-tag';

const GET_BOOK_ID = gql`
query getBookById{
  bookById(id: "book-1") {
    id
    name
    pageCount
    author {
      id
      firstName
      lastName
    }
  }
}`;

const { result, loading, error } = useQuery(GET_BOOK_ID);

以上就是在 Vue 3 中使用 Apollo Client 查询 GraphQL 数据的方法。