SSR
Bitrix24 UI напрямую поддерживает Vue SSR. Это руководство поможет включить её полностью.
Использование
В Nuxt серверная отрисовка (SSR) работает с Bitrix24 UI из коробки. В чистом Vue придётся учесть несколько деталей, чтобы она работала как нужно.
Внедрение цветовых переменных
По умолчанию Bitrix24 UI внедряет в <head> документа цветовые переменные, которые используются всеми компонентами. Во Vue SSR документом библиотека не управляет, поэтому переменные придётся внедрить вручную.
Сделать это можно через @unhead так:
import { createHead, renderSSRHead } from '@unhead/vue/server'
// Создаём head с помощью unhead
const head = createHead()
// Отрисовываем SSR-заголовок и добавляем его в экземпляр SSR-приложения
const payload = await renderSSRHead(head)
app.head.push(payload.headTags)
import { createInertiaApp } from '@inertiajs/vue3'
import createServer from '@inertiajs/vue3/server'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import { createHead, renderSSRHead } from '@unhead/vue/server'
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'
import { createSSRApp, h } from 'vue'
import { renderToString } from 'vue/server-renderer'
import type { DefineComponent } from 'vue'
const appName = import.meta.env.VITE_APP_NAME || 'Laravel x Bitrix24 UI'
createServer(
(page) => {
const head = createHead()
return createInertiaApp({
page,
render: renderToString,
title: (title) => (title ? `${title} - ${appName}` : appName),
resolve: (name) =>
resolvePageComponent(
`./pages/${name}.vue`,
import.meta.glob<DefineComponent>('./pages/**/*.vue')
),
setup: ({ App, props, plugin }) =>
createSSRApp({ render: () => h(App, props) })
.use(plugin)
.use(head)
.use(b24UiPlugin)
}).then(async (app) => {
const payload = await renderSSRHead(head)
app.head.push(payload.headTags)
return app
})
},
{ cluster: true }
)
import { createInertiaApp } from '@inertiajs/vue3'
import createServer from '@inertiajs/vue3/server'
import b24UiPlugin from '@bxshefby/b24ui-nuxt/vue-plugin'
import { createHead, renderSSRHead } from '@unhead/vue/server'
import { resolvePageComponent } from '@adonisjs/inertia/helpers'
import { createSSRApp, h } from 'vue'
import { renderToString } from 'vue/server-renderer'
import type { DefineComponent } from 'vue'
const appName = import.meta.env.VITE_APP_NAME || 'AdonisJS x Bitrix24 UI'
createServer(
(page) => {
const head = createHead()
return createInertiaApp({
page,
render: renderToString,
title: (title) => (title ? `${title} - ${appName}` : appName),
resolve: (name) =>
resolvePageComponent(
`../pages/${name}.vue`,
import.meta.glob<DefineComponent>('../pages/**/*.vue')
),
setup: ({ App, props, plugin }) =>
createSSRApp({ render: () => h(App, props) })
.use(plugin)
.use(head)
.use(b24UiPlugin)
}).then(async (app) => {
const payload = await renderSSRHead(head)
app.head.push(payload.headTags)
return app
})
},
{ cluster: true }
)
Определение цветовой схемы
То же касается определения цветовой схемы. Чтобы при SSR не возникало мерцания из-за разницы в выбранной схеме, схему пользователя нужно определить до инициализации приложения.
Скрипт ниже, добавленный в <head> документа, определяет, использует ли пользователь тёмную тему, и тогда SSR тоже отрисовывается в тёмной теме.
<script>
const theme = localStorage.getItem('vueuse-color-scheme') || 'auto'
if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
@inertiaHead
@vite('resources/js/app.ts')
<script>
const theme = localStorage.getItem('vueuse-color-scheme') || 'auto'
if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
</script>
</head>
<body>
<div class="isolate">
@inertia
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
@inertiaHead()
@vite(['inertia/app/app.ts', `inertia/pages/${page.component}.vue`])
<script>
const theme = localStorage.getItem('vueuse-color-scheme') || 'auto'
if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
</script>
</head>
<body>
@inertia({ class: 'isolate' })
</body>
</html>