- 创建 ApolloClient 实例:
- 在项目的合适位置(例如
src/apollo.js
)创建一个文件来配置 ApolloClient。
- 引入
ApolloClient
和 InMemoryCache
等必要的模块:
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'YOUR_GRAPHQL_SERVER_URL', // GraphQL 服务器的 URL
cache: new InMemoryCache()
});
export default client;
- 在 Vue 组件中使用它发起简单查询:
- 在 Vue 组件中引入
useQuery
钩子(如果使用 Vue Composition API)或 mapQueries
辅助函数(如果使用 Vuex - like 风格)。
- 使用 Vue Composition API:
import { useQuery } from '@apollo/client';
import gql from 'graphql-tag';
- 定义 GraphQL 查询:
const GET_DATA = gql`
query {
// 这里写你的具体查询内容,例如
someData {
field1
field2
}
}
`;
- 在 `setup` 函数中使用 `useQuery`:
export default {
setup() {
const { loading, error, data } = useQuery(GET_DATA);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
{/* 展示数据 */}
{data.someData.map(item => (
<div key={item.id}>
{item.field1} - {item.field2}
</div>
))}
</div>
);
}
};
- 使用 Vuex - like 风格(mapQueries 辅助函数):
import { mapQueries } from '@apollo/client/vue';
import gql from 'graphql-tag';
- 定义 GraphQL 查询:
const GET_DATA = gql`
query {
// 这里写你的具体查询内容,例如
someData {
field1
field2
}
}
`;
- 在 Vue 组件的 `computed` 中使用 `mapQueries`:
export default {
computed: {
...mapQueries({
someDataQuery: {
query: GET_DATA
}
})
}
};
- 在模板中使用查询结果:
<template>
<div>
<div v-if="someDataQuery.loading">Loading...</div>
<div v-if="someDataQuery.error">Error: {{someDataQuery.error.message}}</div>
<div v-if="someDataQuery.data">
<div v-for="item in someDataQuery.data.someData" :key="item.id">
{{item.field1}} - {{item.field2}}
</div>
</div>
</div>
</template>