用 Vue.js + vue-router 創建單頁應用,是非常簡單的。使用 Vue.js ,我們已經可以通過組合組件來組成應用程序,當你要把 vue-router 添加進來,我們需要做的是,將組件(components)映射到路由(routes),然后告訴 vue-router 在哪里渲染它們。
路由的基本實現
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> /* 實現當前 路由導航高亮 */ .router-link-exact-active, .router-link-active { color: red; font-size: 30px; } </style> </head><body> <div id="app"> <!-- 路由的入口,也就是a標簽 --> <router-link to="/home">home</router-link> <router-link to="/about">about</router-link> <!-- 指定頁面中路由的出口,也就是:路由匹配組件將來展示在頁面中的位置 --> <router-view></router-view> </div> <script src="./vue.js"></script> <!-- 引入 路由插件 --> <script src="./node_modules/vue-router/dist/vue-router.js"></script> <script> /* 路由的使用步驟: 1 引入 路由插件的js文件 2 創建幾個組件 3 通過 VueRouter 來創建一個路由的實例,并且在參數中配置好路由規則 4 將 路由實例 與 Vue實例關聯起來,通過 router 屬性 5 在頁面中使用 router-link 來定義導航(a標簽) 路由路口 6 在頁面中使用 router-view 來定義路由出口(路由內容展示在頁面中的位置) */ // Vue中的路由是:哈希值 和 組件的對應關系 // component 方法能夠返回一個對象,用這個對象就可以表示當前組件 const Home = Vue.component('home', { template: `<h1>這是 Home 組件</h1>` }) const About = Vue.component('about', { template: `<h1>這是 About 組件</h1>` }) // 配置路由規則 const router = new VueRouter({ // 通過 routes 來配置路由規則,值:數組 routes: [ // 數組中的每一項表示一個具體的路由規則 // path 用來設置瀏覽器URL中的哈希值 // componet 屬性用來設置哈希值對應的組件 { path: '/home', component: Home }, { path: '/about', component: About }, // redirect 重定向: 讓當前匹配的 / ,跳轉到 /home 對應的組件中, 也就是默認展示: home組件 { path: '/', redirect: '/home' } ] }) var vm = new Vue({ el: '#app', // Vue的配置對象中有一個配置項叫做:router // 用來指定當前要使用的路由 // router: router router }) </script></body></html>重定向
解釋:將 / 重定向到 /home
{ path: '/', redirect: '/home' }
新聞熱點
疑難解答
圖片精選