Вложенные маршруты

Последнее обновление: 29.10.2017

Во Vue.js одни маршруты могут быть вложенными в другие (nested routes), то есть подмаршрутами. Для их использования определим следующую веб-страницу index.html:

<!DOCTYPE html>
<html>
<head>
<title>Маршрутизация Vue.js</title>
<meta charset="utf-8" />
<style>
ul{list-style-type: none;padding: 0;}
li{display: inline-block;}
a{padding: 5px;}
a.router-link-active, li.router-link-active>a {
  color: red;
}
</style>
</head>
<body>
<div id="app">
    <ul>
      <li><router-link to="/" exact>Главная</router-link></li>
      <li><router-link to="/products/phones">Смартфоны</router-link></li>
      <li><router-link to="/products/tablets">Планшеты</router-link></li>
    </ul>
    <router-view></router-view>
</div>
<script src="https://unpkg.com/vue@2.7.14/dist/vue.js"></script>
<script src="https://unpkg.com/vue@2.7.14/dist/vue.js-router/dist/vue-router.js"></script>
<script>
const NotFound = { template: '<h1>Страница не найдена</h1>' }
const Home = { template: '<h1>Главная</h1>' }

const Phones = { template: '<h2>Смартфоны</h2>' }
const Tablets = { template: '<h2>Планшеты</h2>' }
const Products = { template: '<div><h1>Товары</h1><router-view></router-view></div>' }

const routes = [
  { path: '/', component: Home },
  { 
    path: '/products', 
    component: Products,
    children: [
      {
        path: 'phones',
        component: Phones
      },
      {
        path: 'tablets',
        component: Tablets
      }]
    },
    { path: '*', component: NotFound }
];

const router = new VueRouter({
    mode: 'history',
    routes: routes
});

new Vue({
  el: '#app',
  router: router
})
</script>
</body>
</html>

Здесь для одного маршрута установлено два подмаршрута. Для этого применяется свойство children, которое в качестве параметров принимает массив подмаршрутов:

{ 
	path: '/products', 
    component: Products,
    children: [
      {
        path: 'phones',
        component: Phones
      },
      {
        path: 'tablets',
        component: Tablets
      }
	]
}

Родительский маршрут будет использовать компонент Products. Поэтому в шаблоне этого компонента определяется элемент , в который будут помещаться компоненты, которые выбраны для обработки подмаршрутов:

template: '<div><h1>Товары</h1><router-view></router-view></div>'

В итоге пути "products/tablets" и "products/phones" будут сопоставляться с подмаршрутами:

nested routes in vue.js дочерние маршруты vue.js

Также можно задать подмаршрут, который будет обрабатывать запросы к корню родительского маршрута. Такой подмаршрут в качестве значения свойства path должен иметь пустую строку:

<!DOCTYPE html>
<html>
<head>
<title>Маршрутизация Vue.js</title>
<meta charset="utf-8" />
<style>
ul{list-style-type: none;padding: 0;}
li{display: inline-block;}
a{padding: 5px;}
a.router-link-active, li.router-link-active>a {
  color: red;
}
</style>
</head>
<body>
<div id="app">
    <ul>
      <li><router-link to="/" exact>Главная</router-link></li>
      <li><router-link to="/products">Товары</router-link></li>
    </ul>
    <router-view></router-view>
</div>
<script src="https://unpkg.com/vue@2.7.14/dist/vue.js"></script>
<script src="https://unpkg.com/vue@2.7.14/dist/vue.js-router/dist/vue-router.js"></script>
<script>
const NotFound = { template: '<h1>Страница не найдена</h1>' }
const Home = { template: '<h1>Главная</h1>' }

const Phones = { template: '<h2>Смартфоны</h2>' }
const Tablets = { template: '<h2>Планшеты</h2>' }
const Index = { template: `<div>
                            <h3>Выберите категорию</h3>
                            <div><router-link to="/products/phones">Смартфоны</router-link></div>
                            <div><router-link to="/products/tablets">Планшеты</router-link></div>
                            </div>` }
const Products = { template: '<div><h1>Товары</h1><router-view></router-view></div>' }

const routes = [
  { path: '/', component: Home },
  { 
    path: '/products', 
    component: Products,
    children: [
      {
        path: 'phones',
        component: Phones
      },
      {
        path: 'tablets',
        component: Tablets
      },{
        path: '',
        component: Index
      }]
    },
    { path: '*', component: NotFound }
];

const router = new VueRouter({
    mode: 'history',
    routes: routes
});
new Vue({
  el: '#app',
  router: router
})
</script>
</body>
</html>

В данном случае компонент Index будет обрабатывать запросы по пути "/products":

child routes in vuerouter
Помощь сайту
Юмани:
410011174743222
Перевод на карту
Номер карты:
4048415020898850