Начало работы

Создание одностраничного приложения с Vue + Vue Router кажется естественным: с Vue.js мы уже составляем наше приложение из компонентов. При добавлении Vue Router нам нужно только сопоставить наши компоненты с маршрутами и указать Vue Router, где их отображать. Вот пример:
HTML
<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- use the router-link component for navigation. -->
<!-- specify the link by passing the `to` prop. -->
<!-- `<router-link>` will render an `<a>` tag with the correct `href` attribute -->
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
</p>
<!-- route outlet -->
<!-- component matched by the route will render here -->
<router-view></router-view>
</div>
router-link
Обратите внимание, что вместо обычных тегов a, мы используем пользовательский компонент router-link, чтобы создать ссылки. Это позволяет Vue Router изменять URL без перезагрузки страницы, обрабатывать генерацию URL и его кодирование. Мы увидим, как использовать эти возможности позже.
router-view
router-view отобразит компонент, соответствующий URL. Вы можете разместить его в любом месте, чтобы адаптировать его к своему макету.
JavaScript
// 1. Define route components.
// These can be imported from other files
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = VueRouter.createRouter({
// 4. Provide the history implementation to use. We are using the hash history for simplicity here.
history: VueRouter.createWebHashHistory(),
routes, // short for `routes: routes`
})
// 5. Create and mount the root instance.
const app = Vue.createApp({})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)
app.mount('#app')
// Now the app has started!
Вызывая app.use(router), мы получаем к нему доступ как this.$router, а также к текущему маршруту как this.$route внутри любого компонента:
// Home.vue
export default {
computed: {
username() {
// We will see what `params` is shortly
return this.$route.params.username
},
},
methods: {
goToDashboard() {
if (isAuthenticated) {
this.$router.push('/dashboard')
} else {
this.$router.push('/login')
}
},
},
}
Чтобы получить доступ к роутеру или маршруту внутри функции setup, вызовите функции useRouter или useRoute. Мы узнаем больше об этом в разделе Композиционного API.
В документации мы часто будем использовать экземпляр router. Имейте в виду, что this.$router полностью эквивалентно непосредственному использованию экземпляра router, созданного через createRouter. Причина, по которой мы используем this.$router, заключается в том, что мы не хотим импортировать роутер в каждый компонент, которому нужно манипулировать маршрутизацией.
© 2013–present Evan You
Licensed under the MIT License.
https://next.router.vuejs.org/guide/index.html