前言
Vue.js的一大特色就是構建單頁面應用十分方便,既然要方便構建單頁面應用那么自然少不了路由,vue-router就是vue官方提供的一個路由框架。本文主要介紹了Vue-router 2.0的相關內容,分享出來供大家參考學習,下面來看看詳細的介紹:
一、基礎用法:
<div id="app"> <h1>Hello App!</h1> <p> <!-- 使用 router-link 組件來導航. --> <!-- 通過傳入 `to` 屬性指定鏈接. --> <!-- <router-link> 默認會被渲染成一個 `<a>` 標簽 --> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> <!-- 路由出口 --> <!-- 路由匹配到的組件將渲染在這里 --> <router-view></router-view> </div> <template id='foo'> <p>this is foo!</p> </template> <template id='bar'> <p>this is bar!</p> </template>
// 1. 定義(路由)組件。 // 可以從其他文件 import 進來 const Foo = { template:'#foo' }; const Bar = { template:'#bar' }; // 2. 定義路由 // 每個路由應該映射一個組件。 其中"component" 可以是 // 通過 Vue.extend() 創建的組件構造器, // 或者,只是一個組件配置對象。 const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ]; // 3. 創建 router 實例,然后傳 `routes` 配置 // 你還可以傳別的配置參數, 不過先這么簡單著吧。 const router = new VueRouter({ routes:routes }); // 4. 創建和掛載根實例。 // 記得要通過 router 配置參數注入路由, // 從而讓整個應用都有路由功能 const app = new Vue({ router:router }).$mount('#app'); 二、動態路由匹配:
<div id="app"> <h1>Hello App!</h1> <p> <router-link to="/user/foo/post/123">Go to Foo</router-link> <router-link to="/user/bar/post/456">Go to Bar</router-link> </p> <router-view></router-view> </div> <template id='user'> <p>User:{{ $route.params.id }},Post:{{$route.params.post_id}}</p> </template> // 1. 定義組件。 const User = { template:'#user', watch:{ '$route'(to,from){ console.log('從'+from.params.id+'到'+to.params.id); } } }; // 2. 創建路由實例 (可設置多段路徑參數) const router = new VueRouter({ routes:[ { path:'/user/:id/post/:post_id',component:User } ] }); //3. 創建和掛載根實例 const app = new Vue({ router:router }).$mount('#app'); 三、嵌套路由:
<div id="app"> <h1>Hello App!</h1> <p> <router-link to="/user/foo">Go to Foo</router-link> <router-link to="/user/foo/profile">Go to profile</router-link> <router-link to="/user/foo/posts">Go to posts</router-link> </p> <router-view></router-view> </div> <template id='user'> <div> <h2>User:{{ $route.params.id }}</h2> <router-view></router-view> </div> </template> <template id="userHome"> <p>主頁</p> </template> <template id="userProfile"> <p>概況</p> </template> <template id="userPosts"> <p>登錄信息</p> </template>
新聞熱點
疑難解答
圖片精選