- 目录结构:
- 结果图片:
- HTML代码:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body> <div id="app"> <div> <!-- 静态路由 --> <router-link to="/">首页</router-link> <router-link to="/about">关于我们</router-link> <!-- 动态路由 --> <router-link to="/user/apollo">Apollo</router-link> <router-link to="/user/jack">Jack</router-link> </div> <div> <!-- 路由视图 --> <router-view></router-view> </div> </div> <!-- 注意js导入顺序,自己定义的要在下面 --> <script src="../js/vue.js"></script> <script src="../js/vue-router.js"></script> <script src="app.js"></script> </body> </html>
JS代码:
var routes = [ // 静态路由 { path: '/', component: { template: ` <div> <h1>首页</h1> </div> `, }, }, // 静态路由 { path: '/about', component: { template: ` <div> <h1>关于我们</h1> </div> `, }, }, // 动态路由 { // 注意是斜杠'/'后面在冒号 path: '/user/:name', component: { template: ` <div> <!-- 第一种方式:params,动态传参 --> <h1>用户中心:{{ $route.params.name }}</h1> <!-- 第二种方式:query,也就是用问号'?'动态传参 --> <h2>今年:{{ $route.query.age }}岁了</h2> </div> `, }, } ]; // 路由构造 var router = new VueRouter({ routes: routes, }); // 实例 new Vue({ el: '#app', router: router, });