代码下载 [demo【还未上传,等着】](https://)版本信息 项目 Value node版本 24.15.0 @apollo/client 3.14.1 @vue/apollo-composable 4.2.2 graphql 16.14.0
创建项目 // 创建vue项目 npm create vite@ latest my- vue- ts- app-- -- template vue- ts// 引入graphql,apollo-client,@vue/apollo-composable npm install@ vue / apollo- composable@ apollo / client graphql项目结构
配置Apollo 在src下新建一个文件夹【graphql】专门放graphql相关文件 src |- graphql-server// src/graphql/server/index.ts import { ApolloClient, InMemoryCache, createHttpLink, ApolloLink, from} from '@apollo/client' ; // HTTP连接 const httpLink= createHttpLink ( { uri : 'graphql地址' , } ) ; // // setContext 只适合:加 Token 头部 // const authLink = setContext((_, { headers }) => { // return { // headers: { // ...headers, // authorization: localStorage.getItem('token') || '', // }, // }; // }); /** * 多个http配置不同header */ const authLinkToken= new ApolloLink ( ( operation, forward ) => { const context= operation. getContext ( ) ; operation. setContext ( ( ) => ( { headers : { ... context. headers, authorization : localStorage. getItem ( 'token' ) || 'token' , } , } ) ) ; return forward ( operation) ; } ) ; // 修改返回response内部参数 const formatDateLink= new ApolloLink ( ( operation, forward ) => { return forward ( operation) . map ( ( response ) => { // console.log(response); return response; } ) ; } ) ; const apolloClient= new ApolloClient ( { // link: authLink.concat(httpLink), link : from ( [ authLinkToken, formatDateLink, httpLink] ) , cache : new InMemoryCache ( { } ) , } ) ; export default apolloClient; 全局注入Apollo 客户端// src/server/global.ts import apolloClientfrom './index' ; import { provideApolloClient} from '@vue/apollo-composable' ; // 全局注入 Apollo 客户端 provideApolloClient ( apolloClient) ; export { apolloClient} ; // src/main.ts import './graphql/server/global' ;