在登录父组件中嵌套两个字组件 account1和account2,点击按钮后,可以在父组件中切换子组件
- 第一步,创建父组件,父组件中包含两个子组件
- 注意:需要在父组件中设置占位符,用来放置子组件
<template id="tmp1"> <div> <h1>这是登录父组件</h1> <router-link to="/login/account1">子组件account1</router-link> <router-link to="/login/account2">子组件account2</router-link> <router-view></router-view> </div> </template> var login = Vue.extend({ template: '#tmp1' })
- 第二步,创建路由规则
- 子组件的路由规则通过childer属性创建
- 子组件的路由规则中path属性值不要加 /
var routeObj = new VueRouter({
routes: [
{
path: '/login',
component: login,
children: [
{path: 'account1', component: account1},
{path: 'account2', component: account2},
]
}
]
})
- 整体代码
<!DOCTYPE html> <!--suppress ALL --> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <router-view></router-view> </div> <template id="tmp1"> <div> <h1>这是登录父组件</h1> <router-link to="/login/account1">子组件account1</router-link> <router-link to="/login/account2">子组件account2</router-link> <router-view></router-view> </div> </template> <script> var account1 = { template: '<h1>这是子组件Account1111</h1>' } var account2 = { template: '<h1>这是子组件Account2222</h1>' } var login = Vue.extend({ template: '#tmp1' }) var routeObj = new VueRouter({ routes: [ { path: '/login', component: login, children: [ {path: 'account1', component: account1}, {path: 'account2', component: account2}, ] } ] }) var vm = new Vue({ el: '#app', data: {}, methods: {}, router: routeObj }) </script> </body> </html>