# Mastering GraphQL Fragments in Vue 3: Component-Driven Data Fetching



```mermaid
graph TD
    A["❌ Traditional Approach"] --> A1["Monolithic Queries"]
    A1 --> A2["Over-fetching"]
    A1 --> A3["Tight Coupling"]
    A1 --> A4["Implicit Dependencies"]

    B["✅ Fragment Masking"] --> B1["Component-Owned Data"]
    B1 --> B2["Type Safety"]
    B1 --> B3["Data Encapsulation"]
    B1 --> B4["Safe Refactoring"]
```

## Why Fragments Are a Game-Changer

In Part 2, we achieved type safety with GraphQL Code Generator. But our queries are still monolithic—each component doesn't declare its own data needs. This creates several problems:

- **Over-fetching**: Parent components request data their children might not need
- **Under-fetching**: Adding a field means hunting down every query using that type
- **Tight coupling**: Components depend on their parents to provide the right data
- **Implicit dependencies**: Parent components can accidentally rely on data from child fragments
- **Brittle refactoring**: Changing a component's data needs can break unrelated components

Enter GraphQL fragments with **fragment masking**—the pattern that Relay popularized and that Apollo Client 3.12 has made even more powerful. This transforms how we think about data fetching by providing **true data encapsulation** at the component level.

## What Are GraphQL Fragments?

GraphQL fragments are **reusable units of fields** that components can declare for themselves. But they're more than just field groupings—when combined with fragment masking, they provide **data access control**.

```graphql
fragment CountryBasicInfo on Country {
  code
  name
  emoji
  capital
}
```

**Fragment masking** is the key innovation that makes fragments truly powerful. It ensures that:

1. **Data is encapsulated**: Only the component that defines a fragment can access its fields
2. **Dependencies are explicit**: Components can't accidentally rely on data from other fragments
3. **Refactoring is safe**: Changing a fragment won't break unrelated components
4. **Type safety is enforced**: TypeScript prevents accessing fields you didn't request

## Understanding Fragments Through the Spread Operator

If you're familiar with JavaScript's spread operator, fragments work exactly the same way:

```javascript
// JavaScript objects
const basicInfo = { code: "US", name: "United States" };
const fullCountry = { ...basicInfo, capital: "Washington D.C." };
```

```graphql