Vue.js в веб-разработке: от компонента до приложения
Vue.js как основа фронтенд-приложения
Vue.js - JavaScript-фреймворк для создания пользовательских интерфейсов. Его модель основана на реактивности и компонентах. Ниже основной маршрут для нового проекта и альтернативные подходы для частных задач.
Как собрать проект на Vue 3 с Vite и Composition API, чтобы получить масштабируемую структуру?
Основной способ: Vite как сборщик, SFC, Composition API, Vue Router, Pinia.
Шаг 1. Создание проекта
npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
npm install
npm run devJavascript vue (vue.js фреймворк)
Команда создает шаблон с Vue 3 и Vite. После запуска dev-сервер показывает стартовую страницу.
Шаг 2. Компонент с Composition API
<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const double = computed(() => count.value * 2)
</script>
<template>
<button @click='count++'>Счет: {{ count }}</button>
<p>Удвоенное значение: {{ double }}</p>
</template>
Секция script setup делает переменные доступными в шаблоне. ref создает реактивную ссылку, computed пересчитывает значение при изменении count.
Шаг 3. Props и emit
<!-- ChildCard.vue -->
<script setup>
defineProps({ title: String })
const emit = defineEmits(['select'])
function choose() { emit('select', title) }
</script>
<template>
<article @click='choose'>
<h5>{{ title }}</h5>
</article>
</template>
Родительский компонент передает title и слушает событие select. Такой контракт делает компонент независимым.
<!-- Parent.vue -->
<script setup>
import ChildCard from './ChildCard.vue'
function onSelect(value) {
console.log('Выбрано:', value)
}
</script>
<template>
<ChildCard title='Vue' @select='onSelect' />
</template>
Шаг 4. Маршрутизация
npm install vue-router@4
// router.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from './views/HomeView.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: HomeView },
{ path: '/about', component: () => import('./views/AboutView.vue') }
]
})
export default router
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
Ленивая загрузка маршрута уменьшает начальный бандл. Для страницы about код загружается только при переходе.
Шаг 5. Глобальное состояние с Pinia
npm install pinia
// stores/counter.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const double = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, double, increment }
})
// main.js
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).use(createPinia()).mount('#app')
// Component.vue
<script setup>
import { useCounterStore } from './stores/counter'
const counter = useCounterStore()
</script>
<template>
<button @click='counter.increment()'>{{ counter.count }}</button>
<p>{{ counter.double }}</p>
</template>
Типичные ошибки: отсутствие ключа key в v-for, мутация пропсов, прямой импорт store до createPinia, забытый next в навигационном хуке, использование реактивной переменной без .value в script setup.
Решение: проверять консоль Vue Devtools, использовать Pinia до монтирования, возвращать значение из guard, применять toRefs или storeToRefs при деструктуризации store.
Как быстро подключить Vue на статическую страницу без сборщика?
Вариант с CDN подходит для прототипов, виджетов и встраивания в существующую страницу.
<div id='app'>
<button @click='count++'>{{ count }}</button>
</div>
<script src='https://unpkg.com/vue@3/dist/vue.global.js'></script>
<script>
const { createApp, ref } = Vue
createApp({
setup() {
const count = ref(0)
return { count }
}
}).mount('#app')
</script>
Цель: минимальная настройка. Проблемы: глобальная переменная Vue, отсутствие SFC, ограничения CSP, размер runtime. Решение: ESM-сборка, локальный бандл, Vite для production.
Как организовать компонент через Options API, если команда использует старый стиль?
<script>
export default {
data() {
return { count: 0 }
},
computed: {
double() { return this.count * 2 }
},
methods: {
increment() { this.count++ }
}
}
</script>
<template>
<button @click='increment'>{{ count }} / {{ double }}</button>
</template>
Цель: поддержка legacy, простые компоненты. Проблемы: this, сложность переиспользования. Решение: постепенная миграция на Composition API.
Как сделать серверный рендеринг и SEO с Vue?
Nuxt 3 дает SSR, файловую маршрутизацию и автозагрузку компонентов.
npx nuxi@latest init my-nuxt-app
cd my-nuxt-app
npm install
npm run dev
// pages/index.vue
<script setup>
const { data: posts } = await useFetch('https://jsonplaceholder.typicode.com/posts')
</script>
<template>
<ul>
<li v-for='post in posts' :key='post.id'>{{ post.title }}</li>
</ul>
</template>
Цель: SEO, быстрый первый рендер. Проблемы: Node-сервер, гидратация, кэширование. Решение: использовать гибридный рендеринг и routeRules.
Как передать данные глубоко в дерево компонентов без длинной цепочки props?
Provide/inject.
// Parent.vue
<script setup>
import { provide, ref } from 'vue'
const theme = ref('light')
provide('theme', theme)
</script>
// DeepChild.vue
<script setup>
import { inject } from 'vue'
const theme = inject('theme')
</script>
<template>
<p>Тема: {{ theme }}</p>
</template>
Цель: темы, локали, сервисы. Проблемы: неявные зависимости, потеря реактивности при деструктуризации. Решение: передавать ref или computed.
Как переиспользовать логику между компонентами?
Composables.
// composables/useFetch.js
import { ref } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(false)
async function load() {
loading.value = true
try {
const response = await fetch(url)
data.value = await response.json()
} catch (e) {
error.value = e
} finally {
loading.value = false
}
}
return { data, error, loading, load }
}
// UserList.vue
<script setup>
import { onMounted } from 'vue'
import { useFetch } from './composables/useFetch'
const { data, loading, load } = useFetch('https://jsonplaceholder.typicode.com/users')
onMounted(load)
</script>
<template>
<p v-if='loading'>Загрузка...</p>
<ul v-else>
<li v-for='user in data' :key='user.id'>{{ user.name }}</li>
</ul>
</template>
Цель: логика запросов, форм, мыши, localStorage. Проблемы: утечки, гонки запросов. Решение: AbortController, cleanup в onUnmounted.
Как защитить маршрут и выполнить проверку прав?
Vue Router guards.
// router.js
router.beforeEach((to, from, next) => {
const isAuth = localStorage.getItem('token')
if (to.meta.requiresAuth && !isAuth) {
next('/login')
} else {
next()
}
})
// routes
{ path: '/admin', component: AdminView, meta: { requiresAuth: true } }
Цель: закрытые разделы, роли. Проблемы: бесконечные редиректы, отсутствие next. Решение: возвращать значение или использовать async/await.
Расширенные примеры Vue.js
Реактивные примитивы: ref, reactive, computed, watch, watchEffect
import { ref, reactive, computed, watch, watchEffect } from 'vue'
const count = ref(0)
const state = reactive({ name: 'Анна', age: 30 })
const double = computed(() => count.value * 2)
watch(count, (value, oldValue) => {
console.log('count', oldValue, '->', value)
})
watchEffect(() => {
console.log('double', double.value)
})
count.value++
state.age++
double 0 count 0 -> 1 double 2
watch реагирует на конкретный источник, watchEffect запускается сразу и отслеживает зависимости. reactive подходит для объектов, ref для примитивов и заменяемых значений.
Динамические компоненты и KeepAlive
<script setup>
import { shallowRef } from 'vue'
import TabHome from './TabHome.vue'
import TabProfile from './TabProfile.vue'
const tabs = { TabHome, TabProfile }
const current = shallowRef('TabHome')
</script>
<template>
<button @click='current = `TabHome`'>Главная</button>
<button @click='current = `TabProfile`'>Профиль</button>
<KeepAlive>
<component :is='tabs[current]' />
</KeepAlive>
</template>
Переключение вкладок сохраняет локальное состояние, если KeepAlive активен.
shallowRef не делает глубокую реактивность для компонентов, что снижает нагрузку. KeepAlive кэширует экземпляры.
Слоты: именованные и scoped slots
<!-- CardBox.vue -->
<template>
<section class='card'>
<header><slot name='header'>Заголовок</slot></header>
<main><slot>Содержимое</slot></main>
<footer><slot name='footer' :year='2025' /></footer>
</section>
</template>
<CardBox>
<template #header>
<h4>Новости</h4>
</template>
<p>Текст новости</p>
<template #footer='{ year }'>
<small>© {{ year }}</small>
</template>
</CardBox>
Верхний слот выводит Новости, основной слот выводит текст, нижний слот получает year=2025.
Scoped slots передают данные из дочернего компонента в родительский шаблон.
Provide/inject с Symbol и реактивным хранилищем
// keys.js
export const cartKey = Symbol('cart')
// App.vue
<script setup>
import { provide, reactive, computed } from 'vue'
import { cartKey } from './keys'
const cart = reactive({ items: [] })
const total = computed(() => cart.items.reduce((sum, item) => sum + item.price, 0))
provide(cartKey, { cart, total })
</script>
// CartWidget.vue
<script setup>
import { inject } from 'vue'
import { cartKey } from './keys'
const { cart, total } = inject(cartKey)
</script>
<template>
<p>Товаров: {{ cart.items.length }}</p>
<p>Сумма: {{ total }}</p>
</template>
При добавлении товара в cart.items обновляются оба компонента.
Symbol исключает конфликт ключей. Возврат объекта сохраняет реактивность.
Teleport для модальных окон
<script setup>
import { ref } from 'vue'
const open = ref(false)
</script>
<template>
<button @click='open = true'>Открыть</button>
<Teleport to='body'>
<div v-if='open' class='modal'>
<div class='modal__body'>
<p>Модальное окно</p>
<button @click='open = false'>Закрыть</button>
</div>
</div>
</Teleport>
</template>
Модальное окно оказывается в body, не наследует overflow родителя.
Teleport полезен для порталов, уведомлений, контекстных меню.
Transition и TransitionGroup
<script setup>
import { ref } from 'vue'
const show = ref(true)
const items = ref([1, 2, 3])
</script>
<template>
<button @click='show = !show'>Переключить</button>
<Transition name='fade'>
<p v-if='show'>Блок</p>
</Transition>
<TransitionGroup name='list' tag='ul'>
<li v-for='item in items' :key='item'>{{ item }}</li>
</TransitionGroup>
</template>
<style>
.fade-enter-active, .fade-leave-active { transition: opacity 0.3s; }
.fade-enter-from, .fade-leave-to { opacity: 0; }
.list-enter-active, .list-leave-active { transition: all 0.3s; }
.list-enter-from, .list-leave-to { opacity: 0; transform: translateX(30px); }
</style>
Плавное появление и исчезновение, анимация списка.
Классы enter/leave управляют CSS-переходами. TransitionGroup требует key для каждого элемента.
Пользовательские директивы
// focus.js
export const vFocus = {
mounted(el) {
el.focus()
}
}
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { vFocus } from './focus'
createApp(App).directive('focus', vFocus).mount('#app')
<template>
<input v-focus />
</template>
Поле получает фокус после монтирования.
Директива получает el и binding. Для очистки используется unmounted.
Директива на IntersectionObserver
const vVisible = {
mounted(el, binding) {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
binding.value()
observer.disconnect()
}
})
observer.observe(el)
}
}
export default vVisible
<template>
<div v-visible='loadMore'>Конец списка</div>
</template>
loadMore вызывается, когда элемент появляется во viewport.
Такой подход применяется для ленивой загрузки и аналитики видимости.
Composable useLocalStorage
import { ref, watch } from 'vue'
export function useLocalStorage(key, initialValue) {
const stored = localStorage.getItem(key)
const value = ref(stored ? JSON.parse(stored) : initialValue)
watch(value, (next) => {
localStorage.setItem(key, JSON.stringify(next))
}, { deep: true })
return value
}
// Component.vue
<script setup>
import { useLocalStorage } from './useLocalStorage'
const settings = useLocalStorage('settings', { theme: 'light' })
</script>
Значение settings сохраняется между перезагрузками.
Composable инкапсулирует чтение, запись и реактивность.
Vue Router: параметры, props, guards, 404
// router.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/users/:id',
name: 'user',
component: () => import('./UserView.vue'),
props: true,
beforeEnter: (to) => {
if (!Number(to.params.id)) return '/users'
}
},
{ path: '/:pathMatch(.*)*', name: 'not-found', component: NotFound }
]
})
// UserView.vue
<script setup>
defineProps({ id: String })
</script>
<template>
<h3>Пользователь {{ id }}</h3>
</template>
Маршрут /users/42 передает id как prop, /users/abc перенаправляет на /users.
props: true упрощает тестирование. beforeEnter работает до загрузки компонента.
Pinia: store, actions, getters, plugins
// stores/auth.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useAuthStore = defineStore('auth', () => {
const user = ref(null)
const isAdmin = computed(() => user.value?.role === 'admin')
async function login(email, password) {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
})
user.value = await response.json()
}
function logout() {
user.value = null
}
return { user, isAdmin, login, logout }
})
// main.js
import { createPinia } from 'pinia'
const pinia = createPinia()
pinia.use(({ store }) => {
store.$subscribe((mutation, state) => {
console.log('Mutation:', mutation.type)
})
})
createApp(App).use(pinia).mount('#app')
Каждое изменение store логируется через плагин.
Setup-синтаксис Pinia дает refs и computed как обычные переменные.
Render-функции и h()
import { h, ref } from 'vue'
export default {
setup() {
const count = ref(0)
return () => h('button', {
onClick: () => count.value++
}, `Клики: ${count.value}`)
}
}
Кнопка с текстом Клики: 0. После нажатия значение увеличивается.
Render-функции полезны для динамических заголовков и компонентов таблиц.
Suspense и async setup
<!-- AsyncProfile.vue -->
<script setup>
const response = await fetch('https://jsonplaceholder.typicode.com/users/1')
const user = await response.json()
</script>
<template>
<h3>{{ user.name }}</h3>
</template>
<!-- App.vue -->
<template>
<Suspense>
<template #default>
<AsyncProfile />
</template>
<template #fallback>
<p>Загрузка профиля...</p>
</template>
</Suspense>
</template>
Пока данные загружаются, отображается fallback, затем имя пользователя.
Suspense упрощает состояние загрузки для async setup.
TypeScript и defineModel
<!-- CustomInput.vue -->
<script setup lang='ts'>
const model = defineModel<string>({ required: true })
</script>
<template>
<input v-model='model' />
</template>
<!-- Parent.vue -->
<script setup lang='ts'>
import { ref } from 'vue'
const text = ref('')
</script>
<template>
<CustomInput v-model='text' />
<p>{{ text }}</p>
</template>
Двусторонняя привязка без ручного emit update:modelValue.
defineModel доступен в Vue 3.4+ и уменьшает шаблонный код.
Тестирование с Vitest и Vue Test Utils
// Counter.vue
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button @click='count++'>{{ count }}</button>
</template>
// Counter.test.js
import { mount } from '@vue/test-utils'
import { describe, it, expect } from 'vitest'
import Counter from './Counter.vue'
describe('Counter', () => {
it('увеличивает значение', async () => {
const wrapper = mount(Counter)
await wrapper.find('button').trigger('click')
expect(wrapper.text()).toContain('1')
})
})
Тест проходит, текст кнопки содержит 1 после клика.
Vue Test Utils предоставляет mount, trigger, find. Vitest работает с Vite без отдельной конфигурации.
Оптимизация: shallowRef и v-memo
<script setup>
import { shallowRef } from 'vue'
const items = shallowRef([{ id: 1, title: 'A' }, { id: 2, title: 'B' }])
function update() {
items.value = [{ id: 1, title: 'A+' }, { id: 2, title: 'B' }]
}
</script>
<template>
<button @click='update'>Обновить</button>
<ul>
<li v-for='item in items' :key='item.id' v-memo='[item.title]'>
{{ item.title }}
</li>
</ul>
</template>
v-memo пропускает перерисовку li, если title не изменился.
shallowRef снижает глубину отслеживания. v-memo требует массив зависимостей.
Watch с отменой запросов
import { ref, watch } from 'vue'
const query = ref('')
watch(query, async (value, oldValue, onCleanup) => {
const controller = new AbortController()
onCleanup(() => controller.abort())
const response = await fetch(`/search?q=${value}`, { signal: controller.signal })
console.log(await response.json())
})
Предыдущий запрос отменяется при новом вводе, что предотвращает гонки.
onCleanup вызывается перед следующим запуском и при остановке watcher.
defineExpose и template refs
<!-- Child.vue -->
<script setup>
import { ref } from 'vue'
const input = ref(null)
function focus() {
input.value.focus()
}
defineExpose({ focus })
</script>
<template>
<input ref='input' />
</template>
<!-- Parent.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import Child from './Child.vue'
const child = ref(null)
onMounted(() => child.value.focus())
</script>
<template>
<Child ref='child' />
</template>
Родительский компонент получает доступ к методу focus через ref.
defineExpose явно открывает методы и свойства для родителя.
Множественные v-model
<!-- UserForm.vue -->
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>
<template>
<input v-model='firstName' placeholder='Имя' />
<input v-model='lastName' placeholder='Фамилия' />
</template>
<!-- Parent.vue -->
<script setup>
import { ref } from 'vue'
const first = ref('')
const last = ref('')
</script>
<template>
<UserForm v-model:first-name='first' v-model:last-name='last' />
<p>{{ first }} {{ last }}</p>
</template>
Компонент поддерживает два независимых v-model.
Имена моделей преобразуются в события update:firstName и update:lastName.
defineOptions и inheritAttrs
<script setup>
defineOptions({
inheritAttrs: false
})
</script>
<template>
<div class='wrapper'>
<input v-bind='$attrs' />
</div>
</template>
Атрибуты class, placeholder и другие попадают на input, а не на wrapper.
defineOptions заменяет отдельный объект options в script setup.