一个完整的网站不仅仅有一个单页面,那怎么做到工程化后的页面跳转呢?
此时需要用到路由router
router可以译为路由器,在项目开发中是Vue.js 官方的路由管理器。
主要功能:是实现组件的路由配置。
路由router的使用步骤:
1、在src/main.js入口文件中引入相关模块及组件
首先在src下新建个router目录,然后在里面新建个index.js文件,这个文件负责写路由映射并导出,便于管理。
然后
/* 引入并使用模块 */
/*引入router下的index.js文件*/
import router from './router';
/*引入并使用vue-resource网络请求模块*/
import VueResource from 'vue-resource';
Vue.use(VueResource);
此时会报错:找不到vue-router开发依赖,即未安装vue-route模块
控制台报错:找不到依赖,可以运行npm install -save ver-router进行安装
2、安装 vue 路由模块vue-router和网络请求模块vue-resource
因为路由涉及到页面跳转,到后期项目生产环境中也会用到,所以这里用–save保存到项目生产依赖里
webpack安装插件时–save和–save-dev的区别:
3、配置路由选项及渲染App组件(src/main.js入口文件)
new Vue({
el: '#app', /*挂载到#app*/
router, /*添加路由选项*/
components: { App }, /*注册一个全局组件App.vue*/
template: '<App/>' /*渲染在模板上*/
})
4、创建路由,配置路由映射并导出(src/router/index.js)
有两种方法:
方法1:require读取模块
/* 1.引入路由模块并使用 */
import Vue from ‘vue’;
import Router from ‘vue-router’;
/* 2.告诉vue使用vue-router */
Vue.use(Router)
/(1)创建路由实例/
const Home = require(’…/components/Home.vue’);
const About = require(’…/components/About.vue’);
const Tab = require(’…/components/Tab.vue’);
const Error = require(’…/components/Error.vue’);
/注意:此处为components/
/(2)配置路由映射/
const router = new Router({
mode:‘history’,
routes:[
{
path:’/’, /* 默认进入路由(写在第一个) /
redirect:’/home’ / 重定向 /
},
{name:‘home’,path:’/home’,components:Home},
{name:‘about’,path:’/about’,components:About},
{name:‘tab’,path:’/tab’,components:Tab},
{namr:‘error’,path:’/error’,components:Error},
{
path:’’, /* 404错误路由(写在最后一个) /
redirect:’/error’ / 重定向 */
}
]
})
拓展:
(1)上面案例也可以直接导出,即3步融合成2步
(2)路由router-404警告
错误路由重定向如果为home,服务器将不再返回 404 错误页面,因为对于所有路 径都会返回home页面
方法2:import…from…读取模块
注意:这里是component,没加s
5、设置链接router-link(src/App.vue)
使用 router-link 组件来导航,通过传入 to
属性指定链接, 默认会被渲染成一个 <a>
标签
<template>
<div id="app">
<div class="nav">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于我们</router-link>
<router-link to="/tab">动态组件</router-link>
</div>
<div class="area">
/* 路由匹配到的组件将渲染到这里 */
<router-view></router-view>
</div>
</div>
</template>
6、设置路由映射组件渲染router-view(src/App.vue)
路由链接router-link会被渲染成a链接,router-view要想显示对应a链接的页面组件信息,则需要router-view进行渲染展示
<div class="area">
/* 路由匹配到的组件将渲染到这里 */
<router-view></router-view>
</div>
7、去除#(src/router/index.js)
点击链接,此时可以实现页面跳转,但会发现,URL里有#
去除# ,在路由实例里配置,添加mode为history
路由router拓展
(1)单页面富应用(Single Page Application - SPA)
对于vue开发的单页面应用,我们在切换不同的页面的时候,可以发现html永远只有一个,这也真是称之为单页面的原因
(2)懒加载
单页面应用(Single Page Application - SPA) ,通过一个入口index.html,一次性加载(懒加载)所需的资源(js , css , img , font),所有操作通过 js 实现,包括 路由机制、网络请求和界面渲染 ,使用期间无需重新加载其他页面。(懒加载 : 用的时候,再去加载)