标签:
用Vue.js+vue-router创建单页应用是比较简单的。使用Vue.js时,我们就已经把组件组合成一个应用了,当你要把vue-router加进来,只要配置组件和路由映射,然后告诉vue-router在哪里渲染它们。举例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div id="app"> <h1>Hello Vue-router!</h1> <p> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <router-view></router-view> </div> </body> <script src="http://cdn.bootcss.com/vue/2.0.0-rc.8/vue.js"></script> <script src="http://cdn.bootcss.com/vue-router/2.0.0-rc.7/vue-router.js"></script> <script> const Foo = { template: ‘<div>foo</div>‘ } const Bar = { template: ‘<div>bar</div>‘ } const routes = [ { path: ‘/foo‘, component: Foo }, { path: ‘/bar‘, component: Bar } ] const router = new VueRouter({ routes // short for routes: routes }) const app = new Vue({ router }).$mount(‘#app‘); </script> </html>
结果:
可以在 vue-router 的路由路径中使用“动态路径参数”
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div id="app"> <h1>Hello Vue-router!</h1> <p> <router-link to="/foo/first">Go to First</router-link> <router-link to="/foo/second">Go to Second</router-link> </p> <router-view></router-view> </div> </body> <script src="http://cdn.bootcss.com/vue/2.0.0-rc.8/vue.js"></script> <script src="http://cdn.bootcss.com/vue-router/2.0.0-rc.7/vue-router.js"></script> <script> const Foo = { template: ‘<div>foo {{ $route.params.id }}</div>‘ } const routes = [ { path: ‘/foo/:id‘, component: Foo }, ] const router = new VueRouter({ routes // short for routes: routes }) const app = new Vue({ router }).$mount(‘#app‘); </script> </html>
结果:
URL中各段动态路径可以按某种结构对应嵌套各层组件。
例子:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <div id="app"> <p> <router-link to="/user/foo">/user</router-link> <router-link to="/user/foo/profile">/user/profile</router-link> <router-link to="/user/foo/posts">/user/posts</router-link> </p> <router-view></router-view> </div> </body> <script src="http://cdn.bootcss.com/vue/2.0.0-rc.8/vue.js"></script> <script src="http://cdn.bootcss.com/vue-router/2.0.0-rc.7/vue-router.js"></script> <script> const User = { template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <router-view></router-view> </div> ` } const UserHome = { template: ‘<div>Home</div>‘ } const UserProfile = { template: ‘<div>Profile</div>‘ } const UserPosts = { template: ‘<div>Posts</div>‘ } const router = new VueRouter({ routes: [ { path: ‘/user/:id‘, component: User, children: [ { path: ‘‘, component: UserHome }, { path: ‘profile‘, component: UserProfile }, { path: ‘posts‘, component: UserPosts } ] } ] }); const app = new Vue({ router }).$mount(‘#app‘); </script> </html>
结果:
标签:
原文地址:http://www.cnblogs.com/wj204/p/5938066.html