vue2.0路由-适合刚接触新手简单理解
vue路由:vue-router
vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。
下载方式:npm install vue-router
html:
<!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:
<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>
总体:
<!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>