路由拦截分为:
全局路由拦截、局部路由拦截
全局路由拦截:
const router = new VueRouter({
mode: 'history',
routes
})
// 全局拦截
router.beforeEach((to, from, next) => {
if (需要拦截验证的路由) {
if (验证成功) {
// next():不拦截,放行
next()
} else {
next('/login')
}
} else {
next()
}
})
局部路由拦截:
{
path: '/order',
component: OrderView,
meta: {
isKerwinRequired: true
},
beforeEnter: (to, from, next) => {
if (localStorage.getItem('token')) {
// next():不拦截,放行
next()
} else {
next('/login')
}
}
}
路由懒加载
实现原理:将路由相关的组件,不再直接导入了,而是改写成异步组件的写法,只有当函数被调用的时候,才去加载对应的组件内容。
传统配制
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/index.vue'
import Home from '@/views/home/home.vue'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
{ path: '/login', component: Login },
{ path: '/home', component: Home }
]
export default router
rem
rem是一个相对单位,像px,vh,vw等一样,可以用来表示尺寸单位。
rem之所以可以用于自适应布局,是因为rem是一个相对尺寸,它只相对于html根元素来进行计算
所以,在不同的页面大小中,只要改变html根元素的大小,其他所有元素便会跟着改变
扩展:lib-amfe-flexble文件可以使用viewport代替
swiper插件
安装:
- npm i swiper
用法:
- Swiper``SwiperSlide
// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue';
// Import Swiper styles
import 'swiper/css';
指令编写
<div id="app">
<swiper v-if="swiperList.length">
<div class="swiper-slide" v-for="(item,index) in swiperList" :key="index">
<img :src="item" />
</div>
</swiper>
</div>
引入
在项目的src目录中,新建一个request文件夹,然后在里面新建一个http.js和一个api.js文件。http.js文件用来封装我们的axios,api.js用来统一管理我们的接口。
// 在http.js中引入axios
import axios from 'axios'; // 引入axios
import QS from 'qs'; // 引入qs模块
用来序列化post类型的数据,后面会提到
// vant的toast提示框组件,大家可根据自己的ui组件更改。
import { Toast } from 'vant';
切换环境
if (process.env.NODE_ENV == 'development') {
axios.defaults.baseURL = 'https://www.baidu.com';}
else if (process.env.NODE_ENV == 'debug') {
axios.defaults.baseURL = 'https://www.ceshi.com';
}
else if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'https://www.production.com';
}
详情渲染
Vue的执行过程主要分两大阶段:Vue自身的初始化阶段和实例的生命周期管理阶段。
当通过
(function(){
...
// 定义构造函数
function Vue (options) {
this._init(options);
}
// 定义原型方法
Vue.prototype._init = function (options) { ... }
Vue.prototype._update = function () { ... }
...
window.Vue = Vue;
})();
elementui组件库
安装:npm i element-ui -S
CDN引入:
<!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script>