> ## Documentation Index
> Fetch the complete documentation index at: https://inertiajs-vi.tuantq.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Dữ liệu dùng chung

<Warning>Đây là tài liệu Inertia.js v1, phiên bản không còn được duy trì tích cực. Vui lòng tham khảo [tài liệu v3](/v3/getting-started/index).</Warning>

Đôi khi bạn cần truy cập một số dữ liệu cụ thể trên nhiều trang trong ứng dụng. Ví dụ, bạn có thể cần hiển thị người dùng hiện tại trong header của website. Việc truyền thủ công dữ liệu này trong từng response trên toàn ứng dụng khá bất tiện. May mắn là có một lựa chọn tốt hơn: dữ liệu dùng chung.

## Chia sẻ dữ liệu

Tất cả adapter phía máy chủ của Inertia đều cung cấp một cách để đưa dữ liệu dùng chung vào mọi request. Việc này thường được thực hiện bên ngoài controller. Dữ liệu dùng chung sẽ tự động được merge với page props mà controller cung cấp.

Trong ứng dụng Laravel, việc này thường do middleware `HandleInertiaRequests` xử lý; middleware này được tự động cài đặt khi bạn cài [adapter phía máy chủ](/server-side-setup#middleware).

```php theme={null}
class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            // Synchronously...
            'appName' => config('app.name'),

            // Lazily...
            'auth.user' => fn () => $request->user()
                ? $request->user()->only('id', 'name', 'email')
                : null,
        ]);
    }
}
```

Ngoài ra, bạn có thể chia sẻ dữ liệu thủ công bằng phương thức `Inertia::share`.

```php theme={null}
use Inertia\Inertia;

// Synchronously...
Inertia::share('appName', config('app.name'));

// Lazily...
Inertia::share('user', fn (Request $request) => $request->user()
    ? $request->user()->only('id', 'name', 'email')
    : null
);
```

Nên sử dụng dữ liệu dùng chung một cách tiết chế vì toàn bộ dữ liệu dùng chung được gửi kèm trong mọi response.

Page props và dữ liệu dùng chung được merge với nhau, vì vậy hãy namespace dữ liệu dùng chung phù hợp để tránh xung đột.

## Truy cập dữ liệu dùng chung

Sau khi chia sẻ dữ liệu ở phía máy chủ, bạn có thể truy cập dữ liệu đó trong bất kỳ trang hoặc component nào. Sau đây là ví dụ cách truy cập dữ liệu dùng chung trong một layout component.

<CodeGroup>
  ```vue Vue 2 icon="vuejs" theme={null}
  <template>
      <main>
          <header>
              You are logged in as: {{ user.name }}
          </header>
          <article>
              <slot />
          </article>
      </main>
  </template>

  <script>
  export default {
      computed: {
          user() {
              return this.$page.props.auth.user
          }
      }
  }
  </script>
  ```

  ```vue Vue 3 icon="vuejs" theme={null}
  <script setup>
  import { computed } from 'vue'
  import { usePage } from '@inertiajs/vue3'

  const page = usePage()

  const user = computed(() => page.props.auth.user)
  </script>

  <template>
      <main>
          <header>
              You are logged in as: {{ user.name }}
          </header>
          <article>
              <slot />
          </article>
      </main>
  </template>
  ```

  ```jsx React icon="react" theme={null}
  import { usePage } from '@inertiajs/react'

  export default function Layout({ children }) {
      const { auth } = usePage().props

      return (
          <main>
              <header>
                  You are logged in as: {auth.user.name}
              </header>
              <article>
                  {children}
              </article>
          </main>
      )
  }
  ```

  ```html Svelte icon="s" theme={null}
  <script>
      import { page } from '@inertiajs/svelte'
  </script>

  <main>
      <header>
          You are logged in as: {$page.props.auth.user.name}
      </header>
      <article>
          <slot />
      </article>
  </main>
  ```
</CodeGroup>

## Flash message

Một trường hợp sử dụng rất phù hợp khác của dữ liệu dùng chung là flash message. Đây là các message được lưu trong session chỉ cho request kế tiếp. Ví dụ, một cách phổ biến là đặt flash message sau khi hoàn tất một tác vụ và trước khi redirect sang trang khác.

Sau đây là một cách đơn giản để triển khai flash message trong ứng dụng Inertia. Trước tiên, hãy chia sẻ flash message trên mỗi request.

```php theme={null}
class HandleInertiaRequests extends Middleware
{
    public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            'flash' => [
                'message' => fn () => $request->session()->get('message')
            ],
        ]);
    }
}
```

Tiếp theo, hiển thị flash message trong một component frontend, chẳng hạn layout của website.

<CodeGroup>
  ```vue Vue 2 icon="vuejs" theme={null}
  <template>
      <main>
          <header></header>
          <article>
              <div v-if="$page.props.flash.message" class="alert">
                  {{ $page.props.flash.message }}
              </div>
              <slot />
          </article>
          <footer></footer>
      </main>
  </template>
  ```

  ```vue Vue 3 icon="vuejs" theme={null}
  <template>
      <main>
          <header></header>
          <article>
              <div v-if="$page.props.flash.message" class="alert">
                  {{ $page.props.flash.message }}
              </div>
              <slot />
          </article>
          <footer></footer>
      </main>
  </template>
  ```

  ```jsx React icon="react" theme={null}
  import { usePage } from '@inertiajs/react'

  export default function Layout({ children }) {
      const { flash } = usePage().props

      return (
          <main>
              <header></header>
              <article>
                  {flash.message && (
                      <div class="alert">{flash.message}</div>
                  )}
                  {children}
              </article>
              <footer></footer>
          </main>
      )
  }
  ```

  ```html Svelte icon="s" theme={null}
  <script>
      import { page } from '@inertiajs/svelte'
  </script>

  <main>
      <header></header>
      <article>
          {#if $page.props.flash.message}
              <div class="alert">{$page.props.flash.message}</div>
          {/if}
          <slot />
      </article>
      <footer></footer>
  </main>
  ```
</CodeGroup>

***

## Tài liệu chính thức

Bài dịch này được đối chiếu từ [tài liệu Inertia.js v1 chính thức](https://inertiajs.com/docs/v1/the-basics/shared-data). Nếu có khác biệt do phiên bản hoặc cập nhật mới, hãy ưu tiên tài liệu chính thức làm nguồn tham chiếu.
