Vue3中实现GraphQL API请求

Vue3中实现GraphQL API请求

首先安装依赖

pnpm install @apollo/client @vue/apollo-composable graphql graphql-tag

其次创建ApolloClient实例

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core'

// HTTP connection to the API
import {
  ApolloClient,
  createHttpLink,
  InMemoryCache,
} from "@apollo/client/core";
import { setContext } from "@apollo/client/link/context";

// HTTP connection to the API
const httpLink = createHttpLink({
  // You should use an absolute URL here
  uri: "http://localhost:8080/graphql",
});
// 配置请求头
const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  // const token = localStorage.getItem("token");
  const token = "linlin-authentication";
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    },
  };
});
// Cache implementation
const cache = new InMemoryCache();

// Create the apollo client
export const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache,
});

再其次在main.ts中

import { createApp, h, provide } from "vue";
import "./style.css";
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");

最后在组件中使用

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

const count = ref(0)
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)

注意 只能在setup中使用,并且只能在页面加载时setup生命周期自动调用。下面这种方式可以实现点击是触发请求,并且实现了参数传递,除此之外还可使用useLazyQuery代替useQuery实现点击。

import { provideApolloClient, useQuery } from '@vue/apollo-composable';
import gql from 'graphql-tag';
import { defineComponent, reactive, ref } from 'vue';
import { apolloClient } from '../apolloClient';
const GET_BOOK_ID = gql`
query getBookById($id:ID!){
  bookById(id: $id) {
    id
    name
    pageCount
    author {
      id
      firstName
      lastName
    }
  }
}`
export default defineComponent({
  setup() {
    let book = ref()
    let variables = reactive({ id: '' })

    const onClick = (id: string) => {
      console.log("🚀 ~ file: MyComponent.vue:25 ~ onClick ~ id:", id)
      variables.id = id
      console.log("我被点了,发送graphql请求");
      const { result } = provideApolloClient(apolloClient)(() => useQuery(GET_BOOK_ID, variables))
      book.value = result.value
      // const { result } = useQuery(GET_BOOK_ID) // 不可以
      // book.value = result.value
    }
    return {
      book,
      onClick
    }
  }
})

使用useLazyQuery

const {result,load}=useLazyQuery(GET_BOOK_ID,variables)
// template
<button @click="load()">也可以点我</button>

注意 useLazyQueryuserQuery导入的包均来自于包@vue/apollo-composable

配置代码生成

参考

pnpm add -D typescript @graphql-codegen/cli @graphql-codegen/client-preset
# 初始化配置文件
npx graphql-code-generator init

配置文件参考

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "http://localhost:8080/graphql",
  documents: ["src/**/*.vue"],
  generates: {
    "src/types/": {
      preset: "client",
      config: {
        useTypeImports: true,
      },
    },
  },
};
export default config;

修改package.json,在scripts中增加

"generate": "graphql-codegen"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值