×

vue响应式原理

vue响应式原理(vue.js做出来的网页是响应式的吗)

admin admin 发表于2023-03-27 13:14:04 浏览44 评论0

抢沙发发表评论

本文目录

vue.js做出来的网页是响应式的吗


Vue.js 里面有一个功能插件就是有关实现是响应式的 —— 模型只是普通对象,修改它则更新视图。这让状态管理非常简单且直观,不过理解它的原理也很重要,可以避免一些常见问题。多去学习vue里面的功能插件实现效果的功能比较强悍。

能说说vue的响应式原理吗


Vue 是一个 MVVM 框架,核心是双向数据绑定,VM(视图模型)是作为 V(视图) 和 M(模型)的桥梁。下面是对 Vue 响应式(双向数据绑定)的理解,如果错误尽请指出,一起交流,共同进步。

Vue响应式原理核心是 数据劫持,采用 ES5 的 object.defineproperty 的 getter 和 setter 方法。从一个例子出发:

  1. 首先,在Vue初始化阶段,通过 observer 对 data 中的属性进行递归的劫持,包括 name、job_ undergo、a、b等

  2. 在 get阶段也就是初始化视图时,为每一个劫持的属性分配一个 依赖收集器,主要收集当前属性的观察者对象,例子中 name 属性在模板中有两处被使用,那么 name 属性的依赖收集器中就存放两个观察者对象

  3. 当点击按钮时,将 name 修改为 lisi 时,会触发 observer 的 setter 函数,将 value 更新为 lisi 最新值,然后通知依赖收集器数据发生了更新。

  4. 依赖收集就是发布订阅模式,依赖收集器会通知所有的观察者对象,当前name 属性有两个观察者对象。

  5. 观察者对象调用对应的回调函数进行相关的处理和DOM更新

以上是纯响应式原理的分析和总结,下面配一张流程图:


在Vue中如何实现事件响应式进度条组件


Vue.js 里面有一个功能插件就是有关实现是响应式的 —— 模型只是普通对象,修改它则更新视图。这让状态管理非常简单且直观,不过理解它的原理也很重要,可以避免一些常见问题。多去学习vue里面的功能插件实现效果的功能比较强悍。

nexttick原理是什么


简单来说,Vue 在修改数据后,视图不会立刻更新,而是等同一事件循环中的所有数据变化完成之后,再统一进行视图更新。所有同步任务都在主线程上执行,形成一个执行栈(execution context stack)。

主线程之外,还存在一个“任务队列“(task queue)。只要异步任务有了运行结果,就在“任务队列“之中放置一个事件。

一旦“执行栈“中的所有同步任务执行完毕,系统就会读取“任务队列“,看看里面有哪些事件。那些对应的异步任务,于是结束等待状态,进入执行栈,开始执行。主线程不断重复上面的第三步。Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。


vue实现路由跳转的原理是什么,是调用js底层什么方法


前端路由是直接找到与地址匹配的一个组件或对象并将其渲染出来。改变浏览器地址而不向服务器发出请求有两种方式:
1. 在地址中加入#以欺骗浏览器,地址的改变是由于正在进行页内导航
2. 使用H5的window.history功能,使用URL的Hash来模拟一个完整的URL。
当打包构建应用时,Javascript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了。
目录结构
先来看看整体的目录结构
和流程相关的主要需要关注点的就是 components、history 目录以及 create-matcher.js、create-route-map.js、index.js、install.js。下面就从 basic 应用入口开始来分析 vue-router 的整个流程。
import Vue from ’vue’
import VueRouter from ’vue-router’
// 1. 插件
// 安装 《router-view》 and 《router-link》 组件
// 且给当前应用下所有的组件都注入 $router and $route 对象
Vue.use(VueRouter)
// 2. 定义各个路由下使用的组件,简称路由组件
const Home = { template: ’《div》home《/div》’ }
const Foo = { template: ’《div》foo《/div》’ }
const Bar = { template: ’《div》bar《/div》’ }
// 3. 创建 VueRouter 实例 router
const router = new VueRouter({
mode: ’history’,
base: __dirname,
routes: [
{ path: ’/’, component: Home },
{ path: ’/foo’, component: Foo },
{ path: ’/bar’, component: Bar }
]
})
// 4. 创建 启动应用
// 一定要确认注入了 router
// 在 《router-view》 中将会渲染路由组件
new Vue({
router,
template: ` 《div id=“app“》
《h1》Basic《/h1》
《ul》
《li》《router-link to=“/“》/《/router-link》《/li》
《li》《router-link to=“/foo“》/foo《/router-link》《/li》
《li》《router-link to=“/bar“》/bar《/router-link》《/li》
《router-link tag=“li“ to=“/bar“》/bar《/router-link》
《/ul》
《router-view class=“view“》《/router-view》
《/div》
`
}).$mount(’#app’)123456789101112131415161718192021222324252627282930313233343536373839404142
作为插件
上边代码中关键的第 1 步,利用 Vue.js 提供的插件机制 .use(plugin) 来安装 VueRouter,而这个插件机制则会调用该 plugin 对象的 install 方法(当然如果该 plugin 没有该方法的话会把 plugin 自身作为函数来调用);下边来看下 vue-router 这个插件具体的实现部分。
VueRouter 对象是在 src/index.js 中暴露出来的,这个对象有一个静态的 install 方法:
/* @flow */
// 导入 install 模块
import { install } from ’./install’// ...import { inBrowser, supportsHistory } from ’./util/dom’// ...export default class VueRouter {
// ...}
// 赋值 install
VueRouter.install = install
// 自动使用插件if (inBrowser && window.Vue) {
window.Vue.use(VueRouter)
}123456789101112131415161718
可以看到这是一个 Vue.js 插件的经典写法,给插件对象增加 install 方法用来安装插件具体逻辑,同时在最后判断下如果是在浏览器环境且存在 window.Vue 的话就会自动使用插件。
install 在这里是一个单独的模块,继续来看同级下的 src/install.js 的主要逻辑:
// router-view router-link 组件import View from ’./components/view’import Link from ’./components/link’// export 一个 Vue 引用export let _Vue// 安装函数export function install (Vue) {
if (install.installed) return
install.installed = true
// 赋值私有 Vue 引用
_Vue = Vue // 注入 $router $route
Object.defineProperty(Vue.prototype, ’$router’, {
get () { return this.$root._router }
}) Object.defineProperty(Vue.prototype, ’$route’, {
get () { return this.$root._route }
}) // beforeCreate mixin
Vue.mixin({
beforeCreate () { // 判断是否有 router
if (this.$options.router) { // 赋值 _router
this._router = this.$options.router // 初始化 init
this._router.init(this) // 定义响应式的 _route 对象
Vue.util.defineReactive(this, ’_route’, this._router.history.current)
}
}
}) // 注册组件
Vue.component(’router-view’, View)
Vue.component(’router-link’, Link)// ...}12345678910111213141516171819202122232425262728293031323334353637383940414243
这里就会有一些疑问了?
· 为啥要 export 一个 Vue 引用?
插件在打包的时候是肯定不希望把 vue 作为一个依赖包打进去的,但是呢又希望使用 Vue 对象本身的一些方法,此时就可以采用上边类似的做法,在 install 的时候把这个变量赋值 Vue ,这样就可以在其他地方使用 Vue 的一些方法而不必引入 vue 依赖包(前提是保证 install 后才会使用)。
· 通过给 Vue.prototype 定义 $router、$route 属性就可以把他们注入到所有组件中吗?
在 Vue.js 中所有的组件都是被扩展的 Vue 实例,也就意味着所有的组件都可以访问到这个实例原型上定义的属性。
beforeCreate mixin 这个在后边创建 Vue 实例的时候再细说。
实例化 VueRouter
在入口文件中,首先要实例化一个 VueRouter ,然后将其传入 Vue 实例的 options 中。现在继续来看在 src/index.js 中暴露出来的 VueRouter 类:
// ...import { createMatcher } from ’./create-matcher’// ...export default class VueRouter {
// ...
constructor (options: RouterOptions = {}) {
this.app = null
this.options = options
this.beforeHooks =
this.afterHooks =
// 创建 match 匹配函数
this.match = createMatcher(options.routes || )
// 根据 mode 实例化具体的 History
let mode = options.mode || ’hash’
this.fallback = mode === ’history’ && !supportsHistory if (this.fallback) {
mode = ’hash’
} if (!inBrowser) {
mode = ’abstract’
}
this.mode = mode switch (mode) {
case ’history’:
this.history = new HTML5History(this, options.base) break
case ’hash’:
this.history = new HashHistory(this, options.base, this.fallback) break
case ’abstract’:
this.history = new AbstractHistory(this) break
default:
assert(false, `invalid mode: ${mode}`)
}
}
// ...}123456789101112131415161718192021222324252627282930313233343536373839
里边包含了重要的一步:创建 match 匹配函数。
match 匹配函数
匹配函数是由 src/create-matcher.js 中的 createMatcher 创建的:
/* @flow */
import Regexp from ’path-to-regexp’// ...import { createRouteMap } from ’./create-route-map’// ...export function createMatcher (routes: Array《RouteConfig》): Matcher {
// 创建路由 map
const { pathMap, nameMap } = createRouteMap(routes)
// 匹配函数 function match (
raw: RawLocation,
currentRoute?: Route,
redirectedFrom?: Location
): Route {
// ...
} function redirect (
record: RouteRecord,
location: Location
): Route {
// ...
} function alias (
record: RouteRecord,
location: Location,
matchAs: string
): Route {
// ...
} function _createRoute (
record: ?RouteRecord,
location: Location,
redirectedFrom?: Location
): Route { if (record && record.redirect) { return redirect(record, redirectedFrom || location)
} if (record && record.matchAs) { return alias(record, location, record.matchAs)
} return createRoute(record, location, redirectedFrom)
}
// 返回 return match
}
// ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
具体逻辑后续再具体分析,现在只需要理解为根据传入的 routes 配置生成对应的路由 map,然后直接返回了 match 匹配函数。
继续来看 src/create-route-map.js 中的 createRouteMap 函数:
/* @flow */import { assert, warn } from ’./util/warn’import { cleanPath } from ’./util/path’// 创建路由 mapexport function createRouteMap (routes: Array《RouteConfig》): {
pathMap: Dictionary《RouteRecord》,
nameMap: Dictionary《RouteRecord》
} { // path 路由 map
const pathMap: Dictionary《RouteRecord》 = Object.create(null) // name 路由 map
const nameMap: Dictionary《RouteRecord》 = Object.create(null) // 遍历路由配置对象 增加 路由记录
routes.forEach(route =》 {
addRouteRecord(pathMap, nameMap, route)
}) return {
pathMap,
nameMap
}
}// 增加 路由记录 函数function addRouteRecord (
pathMap: Dictionary《RouteRecord》,
nameMap: Dictionary《RouteRecord》,
route: RouteConfig,
parent?: RouteRecord,
matchAs?: string
) {
// 获取 path 、name
const { path, name } = route
assert(path != null, `“path“ is required in a route configuration.`) // 路由记录 对象
const record: RouteRecord = {
path: normalizePath(path, parent),
components: route.components || { default: route.component },
instances: {},
name, parent,
matchAs,
redirect: route.redirect,
beforeEnter: route.beforeEnter,
meta: route.meta || {}
} // 嵌套子路由 则递归增加 记录
if (route.children) {// ...
route.children.forEach(child =》 {
addRouteRecord(pathMap, nameMap, child, record)
})
} // 处理别名 alias 逻辑 增加对应的 记录
if (route.alias !== undefined) { if (Array.isArray(route.alias)) {
route.alias.forEach(alias =》 {
addRouteRecord(pathMap, nameMap, { path: alias }, parent, record.path)
})
} else {
addRouteRecord(pathMap, nameMap, { path: route.alias }, parent, record.path)
}
} // 更新 path map
pathMap[record.path] = record // 更新 name map
if (name) { if (!nameMap[name]) {
nameMap[name] = record
} else {
warn(false, `Duplicate named routes definition: { name: “${name}“, path: “${record.path}“ }`)
}
}
}function normalizePath (path: string, parent?: RouteRecord): string {
path = path.replace(/\/$/, ’’) if (path === ’/’) return path if (parent == null) return path return cleanPath(`${parent.path}/${path}`)
}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
可以看出主要做的事情就是根据用户路由配置对象生成普通的根据 path 来对应的路由记录以及根据 name 来对应的路由记录的 map,方便后续匹配对应。
实例化 History
这也是很重要的一步,所有的 History 类都是在 src/history/ 目录下,现在呢不需要关心具体的每种 History 的具体实现上差异,只需要知道他们都是继承自 src/history/base.js 中的 History 类的:
/* @flow */// ...import { inBrowser } from ’../util/dom’import { runQueue } from ’../util/async’import { START, isSameRoute } from ’../util/route’// 这里从之前分析过的 install.js 中 export _Vueimport { _Vue } from ’../install’export class History {// ...
constructor (router: VueRouter, base: ?string) { this.router = router this.base = normalizeBase(base) // start with a route object that stands for “nowhere“
this.current = START this.pending = null
}// ...}// 得到 base 值function normalizeBase (base: ?string): string { if (!base) { if (inBrowser) { // respect 《base》 tag
const baseEl = document.querySelector(’base’) base = baseEl ? baseEl.getAttribute(’href’) : ’/’
} else { base = ’/’
}
} // make sure there’s the starting slash
if (base.charAt(0) !== ’/’) { base = ’/’ + base

手写实现vue3数据响应式 vue3全新vdom+编译器改进vue3编译器流程\x09vue3 p






摘要
reactive## 关于Vue3





话说,Vue3已经进行到rc4版本了,4月份beta发布的时候前端圈红红火火,不知道大家开始学了没





整理了一些资源,现在开始学习应该还不算晚[狗头]





vue2 响应式原理回顾对象响应化:遍历每个key,通过 Object.defineProperty API定义getter,setter// 伪代码





function observe(){





if(typeof obj !=’object’ || obj == null){





return





}





if(Array.isArray(obj)){





Object.setPrototypeOf(obj,arrayProto)





}else{





const keys = Object.keys()





for(let i=0;i





const key = keys[i]





defineReactive(obj,key,obj[key])





}





}





}





function defineReactive(target, key, val){





observe(val)





Object.defineProperty(obj, key, {





get(){





// 依赖收集





dep.depend()





return val





},





set(newVal){





if(newVal !== val){





observe(newVal)





val = newVal





// 通知更新





dep.notify()





}





}





})





}数组响应化:覆盖数组的原型方法,增加通知变更的逻辑// 伪代码





const originalProto = Array.prototype





const arrayProto = Object.create(originalProto)





[’push’,’pop’,’shift’,’unshift’,’splice’,’reverse’,’sort’].forEach(key=》{





arrayProto[key] = function(){





originalProto[key].apply(this.arguments)





notifyUpdate()





}





})





vue2响应式痛点递归,消耗大





新增/删除属性,需要额外实现单独的API





数组







咨询记录 · 回答于2021-10-30









手写实现vue3数据响应式 vue3全新vdom+编译器改进vue3编译器流程\x09vue3 patc









reactive## 关于Vue3









话说,Vue3已经进行到rc4版本了,4月份beta发布的时候前端圈红红火火,不知道大家开始学了没









整理了一些资源,现在开始学习应该还不算晚[狗头]









vue2 响应式原理回顾对象响应化:遍历每个key,通过 Object.defineProperty API定义getter,setter// 伪代码









function observe(){









if(typeof obj !=’object’ || obj == null){









return









}









if(Array.isArray(obj)){









Object.setPrototypeOf(obj,arrayProto)









}else{









const keys = Object.keys()









for(let i=0;i









const key = keys[i]









defineReactive(obj,key,obj[key])









}









}









}









function defineReactive(target, key, val){









observe(val)









Object.defineProperty(obj, key, {









get(){









// 依赖收集









dep.depend()









return val









},









set(newVal){









if(newVal !== val){









observe(newVal)









val = newVal









// 通知更新









dep.notify()









}









}









})









}数组响应化:覆盖数组的原型方法,增加通知变更的逻辑// 伪代码









const originalProto = Array.prototype









const arrayProto = Object.create(originalProto)









[’push’,’pop’,’shift’,’unshift’,’splice’,’reverse’,’sort’].forEach(key=》{









arrayProto[key] = function(){









originalProto[key].apply(this.arguments)









notifyUpdate()









}









})









vue2响应式痛点递归,消耗大









新增/删除属性,需要额外实现单独的API









数组