vue路由:vue-routerhtml
vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,適合用於構建單頁面應用。vue的單頁面應用是基於路由和組件的,路由用於設定訪問路徑,並將路徑和組件映射起來。傳統的頁面應用,是用一些超連接來實現頁面切換和跳轉的。在vue-router單頁面應用中,則是路徑之間的切換,也就是組件的切換。vue
下載方式:npm install vue-routervue-router
html:npm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue路由</title> <script src="vue.min.js"></script> <script src="vue-router.min.js"></script> </head> <body> <div id="box"> <div> <router-link to="/home">主頁</router-link> <router-link to="/news">新聞</router-link> <router-link to='/about'>關於</router-link> </div> <div> <router-view></router-view> </div> </div> </body> </html>
JavaScript:spa
<script> //組件 const Home = { template:'<h3>我是主頁</h3>' }; const News = { template:'<h3>我是新聞</h3>' } const About = { template:'<h3>我是關於</h3>' } //配置路由 const routes = [ {path:'/home', component :Home}, {path:'/news', component:News}, {path:'/about',component:About}, //重定向 {path:'*',redirect:'/home'} ] //生成路由實例 const router = new VueRouter({ routes }) //掛載到vue上 new Vue({ router, el:'#box' }) </script>
CSS:插件
<style> .router-link-active{ background: #ccc; padding: 5px; text-decoration: none; } </style>
整體:code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue路由</title> <script src="vue.min.js"></script> <script src="vue-router.min.js"></script> <style> .router-link-active{ background: #ccc; padding: 5px; text-decoration: none; } </style> </head> <body> <div id="box"> <div> <router-link to="/home">主頁</router-link> <router-link to="/news">新聞</router-link> <router-link to='/about'>關於</router-link> </div> <div> <router-view></router-view> </div> </div> <script> //組件 const Home = { template:'<h3>我是主頁</h3>' }; const News = { template:'<h3>我是新聞</h3>' } const About = { template:'<h3>我是關於</h3>' } //配置路由 const routes = [ {path:'/home', component :Home}, {path:'/news', component:News}, {path:'/about',component:About}, //重定向 {path:'*',redirect:'/home'} ] //生成路由實例 const router = new VueRouter({ routes }) //掛載到vue上 new Vue({ router, el:'#box' }) </script> </body> </html>