MST

星途 面试题库

面试题:Vue 中如何配置 GraphQL 请求

在一个 Vue 项目中,假设已经安装好了 `@apollo/client` 库,描述如何进行基本的 GraphQL 请求配置,包括创建 ApolloClient 实例以及在 Vue 组件中使用它发起简单查询的步骤。
40.6万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 创建 ApolloClient 实例
    • 在项目的合适位置(例如 src/apollo.js)创建一个文件来配置 ApolloClient。
    • 引入 ApolloClientInMemoryCache 等必要的模块:
import { ApolloClient, InMemoryCache } from '@apollo/client';
  • 创建 ApolloClient 实例:
const client = new ApolloClient({
  uri: 'YOUR_GRAPHQL_SERVER_URL', // GraphQL 服务器的 URL
  cache: new InMemoryCache()
});

export default client;
  1. 在 Vue 组件中使用它发起简单查询
    • 在 Vue 组件中引入 useQuery 钩子(如果使用 Vue Composition API)或 mapQueries 辅助函数(如果使用 Vuex - like 风格)。
    • 使用 Vue Composition API
      • 引入 useQuery
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 辅助函数)
    • 引入 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>