有时候想同时(同级)展示多个视图,而不是嵌套展示,例如创建一个布局,有 sidebar(侧导航) 和 main(主内容) 两个视图,这个时候命名视图就派上用场了。你可以在界面中拥有多个单独命名的视图,而不是只有一个单独的出口。如果 router-view 没有设置名字,那么默认为 default
<!DOCTYPE html> <!-- saved from url=(0077)https://keepfool.github.io/vue-tutorials/06.Router/basic/basic_01.html#!/home --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>abc</title> </head> <body> <div id="app"> <div class="list-group"> <router-link class="list-group-item" to="/home">Go to Foo</router-link> <router-link class="list-group-item" to="/about">Go to Bar</router-link> </div> <router-view name="a"></router-view> <router-view name="b"></router-view> </div> <template id="homea"> <div> <h1>Home</h1> <p>a</p> </div> </template> <template id="homeb"> <div> <h1>Home</h1> <p>b</p> </div> </template> <template id="abouta"> <div> <h1>About</h1> <p>a</p> </div> </template> <template id="aboutb"> <div> <h1>About</h1> <p>b</p> </div> </template> <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script> <script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.min.js"></script> <script> homea = { template: '#homea' }; homeb = { template: '#homeb' }; abouta = { template: '#abouta' }; aboutb = { template: '#aboutb' }; // About = { template: '<div>bar</div>' } routes = [{ path: '/home', components: { a: homea, b: homeb } }, { path: '/about', components: { a: abouta, b: aboutb } } ] router = new VueRouter({ routes: routes // (缩写)相当于 routes: routes }); app = new Vue({ router: router }).$mount('#app'); </script> </body> </html>
注意这样写时不支持的:
{
path: '/about',
components: {
a: "#abouta",
b: "#aboutb"--不能在这里直接用id
}
}