1 安装
首先,通过 npm 安装 vue-router 插件:
npm install --save vue-router安装的插件版本是:vue-router@3.0.2
2 用法
2.1 新建 vue 组件
在 router 目录中,新建 views 目录,然后新建两个 vue 组件(一个页面就对应一个组件)。
index.vue:
<template>
<div>首页</div>
</template><script>
export default {
name: "index.vue"
}
</script>
<style scoped>
</style>
about.vue:
<template>
<div>关于我们</div>
</template><script>
export default {
name: "about"
}
</script>
<style scoped>
</style>
2.2 修改 main.js
// 引入 Vue 框架
import Vue from 'vue'
import VueRouter from 'vue-router';
//引入 hello.vue 组件
import Hello from './hello.vue'//加载 vue-router 插件
Vue.use(VueRouter);
/*定义路由匹配表*/
const Routers = [{
path: '/index',
component: (resolve) => require(['./router/views/index.vue'], resolve)
},
{
path: '/about',
component: (resolve) => require(['./router/views/about.vue'], resolve)
}]
//路由配置
const RouterConfig = {
//使用 HTML5 的 History 路由模式
mode: 'history',
routes: Routers
};
//路由实例
const router = new VueRouter(RouterConfig);
new Vue({
el: '#app',
router: router,
render: h => h(Hello)
})
步骤如下:
加载 vue-router 插件。
定义路由匹配表,每个路由映射到一个组件。
配置路由。
新建路由实例。
在 Vue 实例中引用路由实例。
Routers 中的每一项,都有以下这些属性:
| 属性 | 说明 |
|---|---|
| path | 匹配路径 |
| component | 需要映射的组件 |
webpack 把每一个路由都打包成一个 js 文件。只有在请求该页面时,才会加载这个 js 文件,即按需加载。
如果需要一次性加载,那么可以这样配置:
{
path: '/index',
component: require('./router/views/index.vue')
}
配置了异步路由之后,编译出的页面 js 被称为 chunk,它们默认的命名格式为 0.main.js、1.main.js 等等。
可以在 webpack.config.js 中配置这个 chunk 的命名格式:
output: {
...
//chunk 文件名










