当我们想创建单页面应用时,可以使用`vue-router`进行实现。
cdn引用:
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
使用方法:
1、`vue-router`必须结合组件使用,因为加载的内容是通过组件加载的,变换的是组件。
var index = Vue.extend({ template: "<h1>首页</h1>" }); var find = Vue.extend({ template: "<h1>发现</h1>" }); var our = Vue.extend({ template: "<h1>我们</h1>" })
2、首先创建`VueRouter`对象:let router = new VueRouter()。
3、在`VueRouter`中需要传递`routes`参数,这个参数是一个数组类型,数组中存储的是对象,
对象中至少包含两个属性:`path`,代表`url`,第二个是`component`,代表数据更新的组件。
let router = new VueRouter({ routes: [{ path: "/", component: index, }, { path: "/find", component: find, }, { path: "/our", component: our, } ] })
4、将VueRouter对象添加到Vue实例中: router: router
new Vue({ el: "#app", router: router, })
5、在需要添加导航的地方添加链接: <router-link to="path">导航名称</router-link>,注意`path`必须与VueRouter中的一致。
<li class="active"> <router-link to="/">首页</router-link> </li>
6、指定在网页中哪个地方要被更新。在更新的地方使用:<router-view></router-view>
整体代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"> <title>vue-router的基本使用</title> </head> <body> <div id="app"> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"> <router-link to="/">首页</router-link> </li> <li> <router-link to="/find">发现</router-link> </li> <li> <router-link to="/our">我们</router-link> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <div class="container"> <router-view></router-view> </div> </div> <script> var index = Vue.extend({ template: "<h1>首页</h1>" }); var find = Vue.extend({ template: "<h1>发现</h1>" }); var our = Vue.extend({ template: "<h1>我们</h1>" }) let router = new VueRouter({ routes: [{ path: "/", component: index, }, { path: "/find", component: find, }, { path: "/our", component: our, } ] }) new Vue({ el: "#app", router: router, data: { } }) </script> </body> </html>