Не отображается компонент вложенного маршрута, Vue-Router
Настраиваю маршрутизацию, используя VueRouter, VueJS. Компонент LessonsList отображается, url меняется.router-link работает. Но не отображается вложенный компонент - Lesson. Вместо него компонент 404 ошибки. Страница не найдена. Маршрут при этом такой, каким и должен быть.
Что я делаю не так?
routes.js
const LessonsList = () => import ('./components/Course/LessonsList');
const Lesson = () => import ('./components/Course/Lesson');
const E404 = () => import ('./components/Store/E404');
const routes = [
{
path: '/',
redirect: {name: 'course'}
},
{
name: 'course',
path: '/course',
component: LessonsList,
children: [
{ name: 'lesson', path: 'lesson:id', component: Lesson }
]
},
{
path: '*',
component: E404
}
];
LessonsList.vue
<template>
<ul>
<router-link v-for="(lesson,index) in lessons"
v-bind:key="index"
v-bind:to="'/course' + /lesson/ + lesson.id"
tag="li">
<h2>LessonsList</h2>
</router-link>
</ul>
</template>
Lesson.vue
<template>
<section>
<h4>Lesson</h4>
</section>
</template>
Ответы (1 шт):
Используя Vue Router, необходимо учитывать следующее:
Функциональный компонент
<router-view>отображает компонент, соответствующий данному маршруту. Компоненты внутри<router-view>также могут содержать в шаблоне собственный<router-view>(он будет использован для отображения компонентов вложенных маршрутов).
т.е. в вашем случае в главном компоненте (приложении):
<router-view></router-view>
и в компоненте LessonsList.vue:
<template>
<div>
<h2>Lessons</h2>
<ul>
<li v-for="(lesson,index) in lessons" :key="index">
<router-link
:to="{
name: 'lesson',
params: {
id: lesson.id
}
}"
tag="a"
>{{ lesson.title }}</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</template>
// 1. Определяем компоненты для маршрутов.
// Они могут быть импортированы из других файлов
const LessonsList = Vue.component('LessonsList', {
data() {
return {
lessons: [{
id: 1,
title: "Lesson 1"
},
{
id: 2,
title: "Lesson 2"
},
{
id: 3,
title: "Lesson 3"
}
]
}
},
template: `
<div>
<div>
Lessons
<router-link to="/lessonslist">Перейти к lessonslist</router-link>
</div>
<ul>
<li v-for="(lesson,index) in lessons" :key="index">
<router-link
:to="{
name: 'lesson',
params: {
id: lesson.id
}
}"
tag="a"
>{{ lesson.title }}</router-link>
</li>
</ul>
<router-view></router-view>
</div>
`
})
const Lesson = Vue.component('Lesson', {
template: `
<section>
<h4>Lesson {{ $route.params.id }}</h4>
</section>
`
})
const E404 = Vue.component('E404', {
template: `
<section>
<h4>Error component</h4>
</section>
`
})
// 2. Определяем несколько маршрутов
const routes = [{
path: '/',
redirect: {
name: 'lessonslist'
}
},
{
name: 'lessonslist',
path: '/lessonslist',
component: LessonsList,
children: [{
name: 'lesson',
path: 'lesson:id',
component: Lesson
}]
},
{
path: '*',
component: E404
}
]
// 3. Создаём экземпляр маршрутизатора и передаём маршруты в опции `routes`
const router = new VueRouter({
routes // сокращённая запись для `routes: routes`
})
// 4. Создаём и монтируем корневой экземпляр приложения.
const app = new Vue({
router
}).$mount('#app')
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
Демонстрация Vue Router | текущий url - {{ $route.path }}
<hr>
<!-- отображаем тут компонент, для которого совпадает маршрут -->
<router-view></router-view>
</div>
Всю необходимую информацию вы можете получить из официального руководства Vue Router