Tips: VueRouter 是Vue官方为单应用专门打造的。
接下来看看如何安装VueRouter
。
分别有使用CDN
引入和使用NPM
安装两种方式。
:::: code-tabs
@tab CDN
1
| https://unpkg.com/vue-router@2.0.0/dist/vue-router.js
|
@tab NPM
1
| npm install vue-router@4
|
::::
这里采用CDN的方式。
其基本的使用方法是:
- 使用
router-link
组件来导航,通过to
来跳转指定链接(相当于<a> </a>
标签)。
- 使用
router-view
组件定义路由出口,路由匹配到组件将会渲染到此处。
- 使用
const routes = [{ path, component }]
来定义路由(路径和组件名)。
- 创建和挂载根实例,在 new Vue 中挂载上一步创建的路由实例
router
。
首先用命令获取库文件:
1 2
| wget https://labfile.oss.aliyuncs.com/courses/1262/vue.min.js wget https://labfile.oss.aliyuncs.com/courses/10532/vue-router.js
|
在index.html
中写入:
:collapsed-lines1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="vue.min.js"></script> <script src="vue-router.js"></script> </head>
<body> <div id="app"> <h1>路由的使用</h1> <p> <router-link to="/home">首页</router-link> <router-link to="/hot">热门</router-link> <router-link to="/class">分类</router-link> </p> <router-view></router-view> </div> <script> const Home = { template: "<div>首页</div>" }; const Hot = { template: "<div>热门</div>" }; const Class = { template: "<div>分类</div>" };
const routes = [ { path: "/home", component: Home }, { path: "/hot", component: Hot }, { path: "/class", component: Class }, ];
const router = new VueRouter({ routes, });
const app = new Vue({ router, }).$mount("#app"); </script> </body> </html>
|
页面效果:
::: demo-wrapper no-padding

:::
点击不同的链接后页面只会局部刷新。