Vue3.0 is the latest version of the Vue.js framework, which brings many new features and better performance. One of the biggest changes involves improvements to routing. In Vue3.0, we can easily define sub-routes, let's take a look at how to mount them.
First, we need to create a Vue3.0 application and install Vue Router4.0. The installation command is as follows:
npm install vue-router@4.0.0-beta.7
We need to create a router in the root component and mount it on the Vue instance. Here is some simple sample code:
import { createRouter, createWebHistory } from 'vue-router'; import Home from './components/Home.vue'; import About from './components/About.vue'; const routes = [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', component: About }, { path: '/user', component: () => import(/* webpackChunkName: "user" */ './components/User.vue'), children: [ { path: '', component: () => import(/* webpackChunkName: "user-profile" */ './components/UserProfile.vue') }, { path: 'posts', component: () => import(/* webpackChunkName: "user-posts" */ './components/UserPosts.vue') } ] } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp(App); app.use(router); app.mount('#app');
Here we create an application with three routes: a homepage (Home), an about page (About), and a user page (User).
Did you notice? We added a child route in the routing configuration of the user page. The child route can be added to thechildren
of the parent route like this. In this example, we added two sub-routes:''
and'posts'
.
We now need to add the sub-routing slot in the component template of the user page. Here's a simple example showing how to add a slot for a child route:
User
Notice it? Our slot name is empty. This is the new feature provided by Vue Router 4.0, which will automatically match sub-routes for us and insert them into the corresponding slots.
Finally, we need to add our own slot in the component template of the child route. The following is a simple example:
User Profile
The componentUserProfile.vue
in this example is the component we added to the sub-route of the user page.
Now, we have successfully mounted the sub-router into our Vue application. This feature allows us to add multiple sub-routes in a component, making our application more flexible and powerful.
The above is the detailed content of How to mount sub-routes introduced in vue3.0. For more information, please follow other related articles on the PHP Chinese website!