Vue学习(第六天)
一、runtime-compiler与runtime-only
1.概念
- Runtime+Compiler: recommended for most users(翻译:运行程序+编译器:推荐给大多数用户)
- Runtime-only: about 6KB lighter min+gzip, but templates (or any Vue-specificHTML) are ONLY allowed in .vue files - render functions are required elsewhere(翻译:仅运行程序: 比上面那种模式轻大约 6KB ,但是 template只允许在.vue文件中使用,而其他地方用需要 render 函数)
2.runtime+compiler中vue的运行过程
- 首先将vue中的模板进行解析解析成abstract syntax tree (ast)抽象语法树
- 将抽象语法树在编译成render函数
- 将render函数再翻译成virtual dom(虚拟dom)
- 将虚拟dom显示在浏览器上
3.runtime-only更快的原因
runtime-only比runtime-compiler快,因为它省略了从template到ast再到render的过程
4.注意
runtime-only模式中不是没有写 template,只是把 template 放在了.vue 的文件中了,并有一个叫vue-template-compiler的在开发依赖时将.vue文件中的 template 解析成 render 函数,因为是开发依赖,不在最后生产中,所以最后生产出来的运行的代码没有template
二、什么是后端渲染?什么是后端路由?什么是前端渲染?什么是前端路由?
- 后端渲染:服务器直线渲染好对应的html页面并返回给客户显示,比如jsp
- 后端路由:后端处理ULR和页面之间的映射关系,比如java web开发中的controller
- 前端渲染:浏览器显示的网页中的大部分内容都是由js代码执行后渲染出来的
- 前端路由:随着Ajax的出现,页面交互是不发生刷新的,但是随着SPA(单页富应用程序)的出现,连页面跳转也是无刷新的,从而产生了前端路由
三、单页面富应用
在前后端分离的基础上加了一层前端路由,只向服务器请求一次html+css+js代码,根据前端路由的映射关系,分离出不同路由对应页面的代码,进行渲染,页面切换时,不会再向服务端发送请求。
四、如何修改url而不使得浏览器发生刷新
方式一
//通过hash来修改url
location.hash = 'foo';
方式二
//通过history来修改
history.pushState({},'','home');//入栈
history.back();//出栈
history.replaceState({},'','four');//替换栈顶的元素
history.go(-1);//后退一个页面
history.forward(1);//前进一个页面
五、路由的使用
1.基本使用流程
-
导入插件
import VueRouter from 'vue-router';
-
安装插件
Vue.use(VueRouter);
-
创建路由组件
-
配置映射关系
const routes = [{ path: '', //默认重定向 // 重定向 redirect: '/home', }, { path: '/home', component: () => import('../components/Home'), //懒加载方式 children: [{//子路由关系 path: '', redirect: 'news' //路由的嵌套 默认重定向 }, { path: 'news', component: () => import('../components/HomeNews') }, { path: 'messages', component: () => import('../components/HomeMessages') } ], meta: { title: '首页'//元数据 } }, { path: '/about', component: () => import('../components/About'), meta: { title: '关于' } }, { path: '/user/:userId', component: () => import('../components/User.vue'), meta: { title: '用户' } }, { path: '/profile', component: () => import('../components/Profile'), meta: { title: '档案' } } ];
-
将router对象传入Vue实例中
import router from './router/index.js'
-
使用
<template> <div id="app"> <!-- 相当于a标签 --> <router-link to="/home">首页</router-link> <router-link to="/about">关于</router-link> <!-- 占位符 --> <router-view></router-view> </div> </template>
2. 设置路由的方式
const router = new VueRouter({
routes,
// 修改为history方式
mode: 'history',
});
3.router-link的属性说明
- to:指定跳转的路径
- tag:渲染成什么组件
- repalce:对url路径进行替换
4.router-link-active属性
当前处于活跃状态的router-link的style属性,可以通过创建router时来修改该class的名称
const router = new VueRouter({
routes,
// 修改为history方式
mode: 'history',
linkActiveClass: 'active'
});