> ## 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.

# Thiết lập phía client

<Warning>Bạn đang xem tài liệu Inertia.js v2. Inertia.js v3 đã được phát hành và hiện là phiên bản mặc định. Hãy xem [hướng dẫn nâng cấp](/v3/getting-started/upgrade-guide) để bắt đầu.</Warning>

Sau khi đã [cấu hình framework phía máy chủ](/v2/installation/server-side-setup), bạn cần thiết lập framework phía client. Inertia hiện hỗ trợ React, Vue và Svelte.

<Card icon="laravel" title="Laravel Starter Kit" href="https://laravel.com/docs/starter-kits" arrow="true" cta="Bắt đầu xây dựng">
  Các starter kit của Laravel cung cấp scaffold sẵn dùng cho ứng dụng Inertia mới.

  Đây là cách nhanh nhất để bắt đầu dự án Inertia mới bằng Laravel và Vue hoặc React. Tuy nhiên, nếu muốn cài Inertia thủ công vào ứng dụng, hãy xem tài liệu bên dưới.
</Card>

## Điều kiện tiên quyết

Trước khi cài Inertia, bạn cần cài và cấu hình framework phía client cùng [Vite plugin](https://laravel.com/docs/vite#vue) tương ứng. Có thể bỏ qua phần này nếu ứng dụng đã thiết lập sẵn.

<CodeGroup>
  ```bash Vue icon="vuejs" theme={null}
  npm install vue @vitejs/plugin-vue
  ```

  ```bash React icon="react" theme={null}
  npm install react react-dom @vitejs/plugin-react
  ```

  ```bash Svelte icon="s" theme={null}
  npm install svelte @sveltejs/vite-plugin-svelte
  ```
</CodeGroup>

Sau đó, thêm plugin của framework vào file `vite.config.js`.

<CodeGroup>
  ```js Vue icon="vuejs" theme={null}
  import { defineConfig } from 'vite'
  import laravel from 'laravel-vite-plugin'
  import vue from '@vitejs/plugin-vue'

  export default defineConfig({
      plugins: [
          laravel({
              input: ['resources/js/app.js'],
              refresh: true,
          }),
          vue(),
      ],
  })
  ```

  ```js React icon="react" theme={null}
  import { defineConfig } from 'vite'
  import laravel from 'laravel-vite-plugin'
  import react from '@vitejs/plugin-react'

  export default defineConfig({
      plugins: [
          laravel({
              input: ['resources/js/app.jsx'],
              refresh: true,
          }),
          react(),
      ],
  })
  ```

  ```js Svelte icon="s" theme={null}
  import { defineConfig } from 'vite'
  import laravel from 'laravel-vite-plugin'
  import { svelte } from '@sveltejs/vite-plugin-svelte'

  export default defineConfig({
      plugins: [
          laravel({
              input: ['resources/js/app.js'],
              refresh: true,
          }),
          svelte(),
      ],
  })
  ```
</CodeGroup>

Để biết thêm về cấu hình các plugin này, hãy xem [tài liệu Vite](https://laravel.com/docs/vite#vue) của Laravel.

## Cài đặt

<Steps>
  <Step title="Install dependencies">
    Cài adapter phía client của Inertia tương ứng với framework bạn lựa chọn.

    <CodeGroup>
      ```bash Vue icon="vuejs" theme={null}
      npm install @inertiajs/vue3
      ```

      ```bash React icon="react" theme={null}
      npm install @inertiajs/react
      ```

      ```bash Svelte icon="s" theme={null}
      npm install @inertiajs/svelte
      ```
    </CodeGroup>
  </Step>

  <Step title="Initialize the Inertia app">
    Tiếp theo, cập nhật file JavaScript chính để khởi động ứng dụng Inertia. Để làm việc này, chúng ta sẽ khởi tạo framework phía client với component Inertia cơ sở.

    <CodeGroup>
      ```js Vue icon="vuejs" theme={null}
      import { createApp, h } from 'vue'
      import { createInertiaApp } from '@inertiajs/vue3'

      createInertiaApp({
          resolve: name => {
              const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
              return pages[`./Pages/${name}.vue`]
          },
          setup({ el, App, props, plugin }) {
              createApp({ render: () => h(App, props) })
                  .use(plugin)
                  .mount(el)
          },
      })
      ```

      ```jsx React icon="react" theme={null}
      import { createInertiaApp } from '@inertiajs/react'
      import { createRoot } from 'react-dom/client'

      createInertiaApp({
          resolve: name => {
              const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
              return pages[`./Pages/${name}.jsx`]
          },
          setup({ el, App, props }) {
              createRoot(el).render(<App {...props} />)
          },
      })
      ```

      ```js Svelte icon="s" theme={null}
      import { createInertiaApp } from '@inertiajs/svelte'
      import { mount } from 'svelte'

      createInertiaApp({
          resolve: name => {
              const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true })
              return pages[`./Pages/${name}.svelte`]
          },
          setup({ el, App, props }) {
              mount(App, { target: el, props })
          },
      })
      ```
    </CodeGroup>

    Callback `setup` nhận mọi thứ cần thiết để khởi tạo framework phía client, bao gồm root component `App` của Inertia.
  </Step>
</Steps>

## Cấu hình giá trị mặc định

Bạn có thể truyền object `defaults` vào `createInertiaApp()` để cấu hình giá trị mặc định cho nhiều tính năng. Không cần truyền mặc định cho mọi key, chỉ cần những key bạn muốn điều chỉnh.

```js theme={null}
createInertiaApp({
    // ...
    defaults: {
        form: {
            recentlySuccessfulDuration: 5000,
        },
        prefetch: {
            cacheFor: "1m",
            hoverDelay: 150,
        },
        visitOptions: (href, options) => {
            return {
                headers: {
                    ...options.headers,
                    "X-Custom-Header": "value",
                },
            };
        },
    },
});
```

Callback `visitOptions` nhận URL đích và visit options hiện tại, sau đó trả object chứa các option cần ghi đè. Để biết chi tiết các cấu hình có sẵn, xem tài liệu [form](/v2/the-basics/forms#form-errors), [prefetch](/v2/data-props/prefetching) và [manual visit](/v2/the-basics/manual-visits#global-visit-options).

### Cập nhật cấu hình khi runtime

Bạn cũng có thể cập nhật giá trị cấu hình khi runtime bằng instance `config` được export. Điều này đặc biệt hữu ích khi cần điều chỉnh setting dựa trên preference của người dùng hoặc state ứng dụng.

<CodeGroup>
  ```js Vue icon="vuejs" theme={null}
  import { config } from '@inertiajs/vue3'

  // Set a single value using dot notation...
  config.set('form.recentlySuccessfulDuration', 1000)
  config.set('prefetch.cacheFor', '5m')

  // Set multiple values at once...
  config.set({
      'form.recentlySuccessfulDuration': 1000,
      'prefetch.cacheFor': '5m',
  })
  ```

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

  // Set a single value using dot notation...
  config.set('form.recentlySuccessfulDuration', 1000)
  config.set('prefetch.cacheFor', '5m')

  // Set multiple values at once...
  config.set({
      'form.recentlySuccessfulDuration': 1000,
      'prefetch.cacheFor': '5m',
  })

  // Get a configuration value...
  const duration = config.get('form.recentlySuccessfulDuration')
  ```

  ```js Svelte icon="s" theme={null}
  import { config } from '@inertiajs/svelte'

  // Set a single value using dot notation...
  config.set('form.recentlySuccessfulDuration', 1000)
  config.set('prefetch.cacheFor', '5m')

  // Set multiple values at once...
  config.set({
      'form.recentlySuccessfulDuration': 1000,
      'prefetch.cacheFor': '5m',
  })

  // Get a configuration value...
  const duration = config.get('form.recentlySuccessfulDuration')
  ```
</CodeGroup>

## Resolve component

Callback `resolve` cho Inertia biết cách tải một page component. Nó nhận tên trang (chuỗi) và trả về module page component. Cách triển khai callback này phụ thuộc vào bundler bạn đang sử dụng (Vite hoặc Webpack).

<CodeGroup>
  ```js Vue icon="vuejs" theme={null}
  // Vite
  resolve: name => {
      const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
      return pages[`./Pages/${name}.vue`]
  },

  // Webpack
  resolve: name => require(`./Pages/${name}`),
  ```

  ```js React icon="react" theme={null}
  // Vite
  resolve: name => {
      const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
      return pages[`./Pages/${name}.jsx`]
  },

  // Webpack
  resolve: name => require(`./Pages/${name}`),
  ```

  ```js Svelte icon="s" theme={null}
  // Vite
  resolve: name => {
      const pages = import.meta.glob('./Pages/**/*.svelte', { eager: true })
      return pages[`./Pages/${name}.svelte`]
  },

  // Webpack
  resolve: name => require(`./Pages/${name}.svelte`),
  ```
</CodeGroup>

Mặc định, chúng tôi khuyến nghị eager load component để tạo một JavaScript bundle duy nhất. Nếu muốn lazy-load component, xem tài liệu [code splitting](/v2/advanced/code-splitting).

Package `laravel-vite-plugin` cũng cung cấp helper [`resolvePageComponent`](https://laravel.com/docs/vite#inertia) có thể dùng để resolve page component.

<CodeGroup>
  ```js Vue icon="vuejs" theme={null}
  import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'

  resolve: name => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
  ```

  ```js React icon="react" theme={null}
  import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'

  resolve: name => resolvePageComponent(`./Pages/${name}.jsx`, import.meta.glob('./Pages/**/*.jsx')),
  ```

  ```js Svelte icon="s" theme={null}
  import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'

  resolve: name => resolvePageComponent(`./Pages/${name}.svelte`, import.meta.glob('./Pages/**/*.svelte')),
  ```
</CodeGroup>

## Định nghĩa root element

Mặc định, Inertia giả định root template của ứng dụng có root element với `id` là `app`. Nếu root element của ứng dụng có `id` khác, bạn có thể cung cấp nó bằng thuộc tính `id`.

```js theme={null}
createInertiaApp({
    id: 'my-app',
    // ...
})
```

Nếu thay đổi `id` của root element, hãy nhớ cập nhật cả [phía máy chủ](/v2/installation/server-side-setup#root-template).

## Phần tử script cho dữ liệu trang

Mặc định, Inertia lưu dữ liệu trang ban đầu trong attribute `data-page` trên root element. Bạn có thể cấu hình Inertia dùng phần tử `<script type="application/json">` thay thế; cách này nhanh hơn một chút và dễ kiểm tra hơn trong devtools của trình duyệt.

```js theme={null}
createInertiaApp({
    // ...
    defaults: {
        future: {
            useScriptElementForInitialPage: true,
        },
    },
})
```

Nếu dùng server-side rendering, hãy nhớ cập nhật cả [SSR entry point](/v2/advanced/server-side-rendering#add-server-entry-point). Người dùng Laravel cũng nên đặt config `inertia.use_script_element_for_initial_page` thành `true` để Blade directive `@inertia` xuất ra phần tử script.

***

## 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 v2 chính thức](https://inertiajs.com/docs/v2/installation/client-side-setup). 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.
