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>
注意
useLazyQuery
和userQuery
导入的包均来自于包@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"