Перейти к основному содержимому

Vue — Router, Pinia и Vite


Создание проекта

npm create vue@latest my-app
cd my-app && npm install && npm run dev

При инициализации включите Router и Pinia — они сразу попадут в шаблон.

Структура (упрощённо):

src/
main.js
App.vue
views/
components/
router/index.js
stores/

Vue Router

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import Notes from '../views/Notes.vue';

export default createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/notes', component: Notes },
],
});
<router-link to="/notes">Заметки</router-link>
<router-view />

Pinia — state

// stores/notes.js
import { defineStore } from 'pinia';

export const useNotesStore = defineStore('notes', {
state: () => ({ items: [], loading: false }),
actions: {
async fetchAll() {
this.loading = true;
const res = await fetch('http://127.0.0.1:3000/notes');
this.items = await res.json();
this.loading = false;
},
},
});
<script setup>
import { useNotesStore } from '@/stores/notes';
const store = useNotesStore();
</script>

Fullstack и CORS — 264.


Vite

  • npm run dev — HMR
  • npm run build — production в dist/
  • vite.config.js — proxy на API в dev (как у React)

Связанные материалы