- 1. 引言
- 2. 什么是vue-router
- 2. vue-router案例
- 2.1 创建项目
- 2.1.1 项目初始化
- 2.1.2 新增需要跳转的两个模块
- 2.2 vue-router路由配置
- 2.2.1 安装vue-router插件
- 2.2.2 配置路由表
- 2.2.3 导入声明
- 2.3 使用路由
通过前面的章节,我们已经学会了使用webpack
来对vue
项目进行打包,有兴趣的同学可以参阅下:
- 《Vue系列教程(01)- 前端发展史》
- 《Vue系列教程(02)- Vue环境搭建、项目创建及运行》
- 《Vue系列教程(03)- Vue开发利器VsCode》
- 《Vue系列教程(04)- VsCode断点调试》
- 《Vue系列教程(05)- 基础知识快速补充(html、css、js)》
- 《Vue系列教程(06)- Vue调试神器(vue-devtools)》
- 《Vue系列教程(07)- Vue第一个程序(MVVM模式的引入)》
- 《Vue系列教程(08)- 基本语法》
- 《Vue系列教程(09)- 事件绑定》
- 《Vue系列教程(10)- Model数据内容双向绑定》
- 《Vue系列教程(11)- 组件详解》
- 《Vue系列教程(12)- Axios异步通信》
- 《Vue系列教程(13)- 计算属性(computed)》
- 《Vue系列教程(14)- 插槽(slot)》
- 《Vue系列教程(15)- 事件内容分发($emit)》
- 《Vue系列教程(16)- 模块打包器(webpack)》
本文主要讲解的是vue
直接的页面跳转,即使用路由vue-router
来实现。
Vue Router
是Vue.js
官方的路由管理器
它和Vue.js
的核心深度集成, 让构建单页面应用变得简单
①新建vue-router-demo
项目,并使用vscode
打开(open
): ②菜单栏:
Terminal -> new Terminal
,并输入命令,并选择Vue 2
:
vue create vue-router-demo
③创建成功:
④ 删除
components
文件夹里面的HelloWorld.vue
文件: ⑤ 修改
App.vue
文件,内容如下:
App页面
export default {
name: 'App'
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
2.1.2 新增需要跳转的两个模块
路由需要跳转到指定的模块,下面来定义需要跳转到的两个模块。
①在components
文件夹里新建两个文件,Content.vue
和Main.Vue
: ②
Content.vue
的内容如下:
内容页
export default {
name: "Content"
}
h1 {
color: orange;
}
③ Main.vue
的内容如下:
首页
export default {
name: "Main"
}
h1 {
color: cornflowerblue;
}
2.2 vue-router路由配置
2.2.1 安装vue-router插件
① 首先安装vue-router
路由插件,进入当前项目,命令行输入:
cd vue-router-demo/
npm install vue-router --save-dev
② 可以看到在node-modules
里新增了vue-router
依赖:
在src
目录下,新建一个router
文件夹,专门存放路由,配置路由index.js
,如下:
import Vue from 'vue'
//导入路由插件
import Router from 'vue-router'
//导入上面定义的组件
import Content from '../components/Content'
import Main from '../components/Main'
//安装路由
Vue.use(Router);
//配置路由
export default new Router({
routes: [
{
//路由路径
path: '/content',
//路由名称
name: 'content',
//跳转到组件
component: Content
}, {
//路由路径
path: '/main',
//路由名称
name: 'main',
//跳转到组件
component: Main
}
]
});
2.2.3 导入声明
如果在一个模块化工程中使用它,必须要通过Vue.use()
明确地安装路由功能,即在main.js
文件声明导入使用vue-router
,完整代码如下:
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router' // 导入VueRouter模块
//导入上面创建的路由配置目录
import router from './router' //自动扫描里面的路由配置
Vue.use(VueRouter); // 使用VueRouter模块
// 关闭生产模式下给出的提示
Vue.config.productionTip = false;
new Vue({
el: '#app',
router,
components: {App},
template: ''
})
2.3 使用路由
① 在App.vue
里使用路由,完整代码如下:
首页
内容
export default {
name: "App",
};
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
② 运行程序
npm run serve
③ 浏览器输入地址:http://localhost:8080/ ,可以看到
默认加载点击首页点击内容


最后,运行的时候,控制台如果出现如下错误,解决方案可以查看:https://segmentfault.com/a/1190000006435886