Vue.js 源码剖析-响应式原理 学习的心得体会+学习笔记

心得体会

不知不觉在拉钩教育大前端高薪训练营已经学习2个多月了,在这两个多月的学习中,自己收获了很多,不仅养成了每次学习时都保证高质量的记好学习笔记的习惯,而且对自己整个的前端基础知识进行了巩固,对基础知识有了更深的理解,勉强做到了知其然,更知其所以然。

接下来我想谈下拉钩教育大前端高薪训练营的课程体系:这门课的内容非常的好,为什么这么说呢?原因有以下几点:

  • 1.课程的深度做的足够好:课程不仅会教同学们怎么使用前端经常使用的框架(vue、react 和 anguler),而且更会教为什么是这样用这些框架。最令人惊喜的是老师会配合 xmind(框架的执行栈的流程图) 和浏览器的断点调试(js在浏览器中的执行过程和渲染过程整个的走一遍)来加深对源码的理解和记忆,并激发我们新的问题和思考。还有像 promise A+ 的代码会带着我们理清整个思路,然后自己实现一遍;webpack 核心内容的讲解以及 怎样手写一个自己的 loader 和 plugin 等等,这里只是做举例说明,太多了就不一一赘述了。
  • 2.课程的广度也非常的好:
    • 1)会讲到 JS 的基础知识并对这些基础知识进行加深和巩固;
    • 2)其次会讲到前端的三大框架(vue、react 和 angular),这三个框架不是泛泛而谈,是讲的很深的那种;
    • 3)还会讲到前端工程化的东西,分别从脚手架工具、自动化构建、模块化开发、规范化标准四个维度介绍前端工程化具体该如何落地、如何实践,以此应对复杂前端应用的开发和维护过程,提高开发者的工作效率,降低项目维护成本,从而更好地适应大前端时代下的前端开发工作;
    • 4)Node.js全栈开发:带你打通前后端边界,掌握前端开发的新舞台:Node.js,通过 Node.js 平台及其相关技术完成应用程序的服务端开发,其中也会涉及目前主流的一些标准和框架,例如 GraphQL、Egg.js,掌握这些后,你可以完成整个网站或 App 的前后端开发,跻身成为全栈型的前端人才。
    • 5)以技术专题的形式学习很多具有趋势性的技术,例如:Serverless、PWA、微前端、数据可视化等等。通过这些技术专题的学习把握技术走势,同时也为你的技能增添闪光点。
    • 6)前端常用的算法
  • 3.讲师的质量也非常的高,讲师的对课程的要求也非常的高,目前讲师经验都非常丰富,汪老师、教瘦、鸠摩智、Storm 目前都是资深技术前端专家。
    • 1)汪磊曾任某知名电商团队技术总监,还是第一届 HTML5 中国产业联盟特邀嘉宾,最早一代小程序开发人员,小程序内测第二天就研发了国内首套小程序教程
    • 2)鸠摩智 曾任职于中国网库、北京因脉科技等公司,担任项目经理;
    • 3)教瘦 十来年前后端开发经验,精通各类客户端开发技术

除此之外,我们还有两位助教老师24小时在群内答疑,有疑惑的地方,就可以立马去群里问助教老师,老师会看到问题就会立马回复,如果是代码执行问题,还会把你的代码下载下来亲自运行排查,真的是助教中的良心。班主任小雪美女也会在群里每天督促同学们交作业,遇到作业提交问题、听课问题都可以直接找班主任老师(PS:小雪美女还会经常发些鸡汤,我都快喝醉了,哈哈哈哈哈哈哈)。

在拉钩教育大前端课程中,只要你能坚持下来(对自己的期待吧,希望自己以后无论做任何事,都能坚持到最后)你就会遇见更好的自己。

任务一:Vue.js 源码剖析-响应式原理。xmind文件见:https://github.com/smallSix6/fed-e-task-liuhuijun/tree/master/fed-e-task-03-02

1、Vue 的不同构建版本

  • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jlUiYQW3-1596333240773)(…/images/vueAllJs.png)]
  • Full:包含编译器和运行时的构建。
  • 编译器:负责将模板字符串编译为JavaScript渲染函数的代码。
  • 运行时:负责创建Vue实例,渲染和修补虚拟DOM等的代码。基本上,所有内容都减去编译器。
  • UMD:UMD构建可通过script标签直接在浏览器中使用。来自 https://unpkg.com/vue 的 Unpkg CDN的默认文件是Runtime + Compiler UMD构建(vue.js)。
  • CommonJS的:CommonJS的建立旨在用于与旧捆扎机像 browserify或的WebPack 1。这些捆绑器(pkg.main)的默认文件是“仅运行时” CommonJS构建(vue.runtime.common.js)。
  • ES模块:ES模块版本旨在与现代捆绑器(例如 webpack 2或汇总)一起使用。这些捆绑程序(pkg.module)的默认文件是“仅运行时ES模块”构建(vue.runtime.esm.js)。

2、入口文件

  • 寻找入口文件
    • 查看 dist/vue.js 的构建过程
  • 执行构建
"dev": "rollup -w -c scripts/config.js --sourcemap --environment TARGET:web-full-dev",
  • script/config.js 的执行过程
    • 作用:生成 rollup 构建的配置文件
    • 使用环境变量 TARGET=web-full-de
    // 判断环境变量是否有 TARGET
    // 如果有的话,使用 gitConfig() 生成 rollup 配置文件
    if (process.env.TARGET) {module.exports = genConfig(process.env.TARGET)
    } else {exports.getBuild = genConfigexports.getAllBuilds = () => Object.keys(builds).map(genConfig)
    }
    
  • 最后生成 src/platforms/web/entry-runtime-with-compiler.js 文件
  • 通过查看源码解决下面问题
    • 观察以下代码,通过阅读源码,回答在页面上输出的结果
    const vm = new Vue({el: '#app'template: '<h3> Hello Template </h3>,render (h) {return h('h4', 'Hello Render')}
    })
    
  • 阅读源码记录
    • el 不能是 body 或者 html 标签
    • 如果没有 render, 把 template 转换成 render 函数
    • 如果有 render 方法,直接调用 mount 挂载 DOM
Vue.prototype.$mount = function(el ? : string | Element,// 非 ssr 情况下为 false, ssr 时候为 truehydrating ? : boolean
): Component {// 获取 el 对象el = el && query(el)/* istanbul ignore if */if (el === document.body || el === document.documentElement) {process.env.NODE_ENV !== 'production' && warn(`Do not mount Vue to <html> or <body> - mount to normal elements instead.`)return this}const options = this.$options// resolve template/el and convert to render functionif (!options.render) {...}// 调用 mount 方法,渲染 DOMreturn mount.call(this, el, hydrating)
}
  • 页面渲染流程的 Call Stack 为:
    • Vue
    • Vue._init
    • Vue.$mount

3、Vue 初始化的过程

  • 四个导出 Vue 的模块
    • src/platforms/web/entry-runtime-with-compiler.js
      • web 平台相关的入口
      • 重写了平台相关的 $mount() 方法
      • 注册了 Vue.compile() 方法,传递一个 HTML 字符串返回 render 函数
    • src/platforms/web/runtime/index.js
      • web 平台相关
      • 注册和平台相关的全局指令:v-model、v-show
      • 注册和平台相关的全局组件:v-transition、v-transition-group
      • 全局方法:
        • patch:把虚拟 DOM 转换成真实 DOM
        • $mount: 挂载方法
    • src/core/index.js
      • 与平台无关
      • 设置了 vue 的静态方法, initGlobalAPI(Vue)
  • src/core/instance/index.js
    • 与平台无关
    • 定义了构造函数,调用了 this._init(options) 方法
    • 给 Vue 中混入了常用的实例成员
    // 此处不用 class 的原因是因为方便后续给 Vue 实例混入实例成员
    function Vue(options) {if (process.env.NODE_ENV !== 'production' &&!(this instanceof Vue)) {warn('Vue is a constructor and should be called with the `new` keyword')}// 调用 _init() 方法this._init(options)
    }// 注册 vm 的 _init() 方法,初始化 vm
    initMixin(Vue)// 注册 vm 的 $data/$props/$set/$delete/$watch
    stateMixin(Vue)// 初始化事件相关方法// $on/$once/$off/$emit
    eventsMixin(Vue)// 初始化生命周期相关的混入方法
    // _update/$forceUpdate/$destroy
    lifecycleMixin(Vue)// 混入 render// $nextTick/_render
    renderMixin(Vue)export default Vue
    

4、Vue 初始化——静态成员

  • src/core/global-api/index.js
    • 设置 Vue 的静态方法,initGlobalAPI(Vue)
     export function initGlobalAPI(Vue: GlobalAPI) {// configconst configDef = {}configDef.get = () => configif (process.env.NODE_ENV !== 'production') {configDef.set = () => {warn('Do not replace the Vue.config object, set individual fields instead.')}}// 初始化 Vue.config 对象// 在 src/platforms/web/runtime/index.js 里设置了 config 属性Object.defineProperty(Vue, 'config', configDef)// exposed util methods.// NOTE: these are not considered part of the public API - avoid relying on// them unless you are aware of the risk.Vue.util = {warn,extend,mergeOptions,defineReactive}Vue.set = setVue.delete = delVue.nextTick = nextTick// 2.6 explicit observable APIVue.observable = < T > (obj: T): T => {observe(obj)return obj}Vue.options = Object.create(null)ASSET_TYPES.forEach(type => {Vue.options[type + 's'] = Object.create(null)})// this is used to identify the "base" constructor to extend all plain-object// components with in Weex's multi-instance scenarios.Vue.options._base = Vueextend(Vue.options.components, builtInComponents)// 注册 Vue.use(),用来注册插件initUse(Vue)// 注册 Vue.mixin() 实现混入    initMixin(Vue)// 注册 Vue.extend() 基于传入的 options 返回一个组件的构造函数initExtend(Vue)// 注册 Vue.directive()、Vue.component()、Vue.filter()initAssetRegisters(Vue)}
    
    • initUse(Vue) 注册 Vue.use(),用来注册插件
    import { toArray } from '../util/index'
    export function initUse (Vue: GlobalAPI) {Vue.use = function (plugin: Function | Object) {const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))if (installedPlugins.indexOf(plugin) > -1) {return this}// additional parameters// 把数组中的第一个元素(plugin)去除const args = toArray(arguments, 1)// 把 this(vue) 插入第一个元素的位置args.unshift(this)if (typeof plugin.install === 'function') {plugin.install.apply(plugin, args)} else if (typeof plugin === 'function') {plugin.apply(null, args)}installedPlugins.push(plugin)return this}
    }
    

5、Vue 初始化——实例成员

  • src/core/instance/index.js
// 此处不用 class 的原因是因为方便后续给 Vue 实例混入实例成员
function Vue(options) {if (process.env.NODE_ENV !== 'production' &&!(this instanceof Vue)) {warn('Vue is a constructor and should be called with the `new` keyword')}// 调用 _init() 方法this._init(options)
}// 注册 vm 的 _init() 方法,初始化 vm
initMixin(Vue)// 注册 vm 的 $data/$props/$set/$delete/$watch
stateMixin(Vue)// 初始化事件相关方法// $on/$once/$off/$emit
eventsMixin(Vue)// 初始化生命周期相关的混入方法
// _update/$forceUpdate/$destroy
lifecycleMixin(Vue)// 混入 render// $nextTick/_render
renderMixin(Vue)export default Vue

6、Vue 初始化——实例成员——init

  • initMixin(Vue) 注册 vm 的 _init() 方法,初始化 vm
export function initMixin(Vue: Class < Component > ) {// 给 Vue 实力增加 init() 方法// 合并 options 并且初始化操作Vue.prototype._init = function(options ? : Object) {const vm: Component = this// a uidvm._uid = uid++let startTag, endTag/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {startTag = `vue-perf-start:${vm._uid}`endTag = `vue-perf-end:${vm._uid}`mark(startTag)}// a flag to avoid this being observedvm._isVue = true// merge optionsif (options && options._isComponent) {// optimize internal component instantiation// since dynamic options merging is pretty slow, and none of the// internal component options needs special treatment.initInternalComponent(vm, options)} else {vm.$options = mergeOptions(resolveConstructorOptions(vm.constructor),options || {},vm)}/* istanbul ignore else */if (process.env.NODE_ENV !== 'production') {initProxy(vm)} else {vm._renderProxy = vm}// expose real selfvm._self = vm// vm 的生命周期相关变量初始化// $children/$parent/$root/$refsinitLifecycle(vm)// vm 的事件监听初始化,父组件绑定在当前组件上的事件initEvents(vm)// vm 的编译 render 初始化// $slot/$scopedSlots/_c/$createElement/$attrs/$listenrsinitRender(vm)// beforeCreate 生命钩子的回调callHook(vm, 'beforeCreate')// 把 inject 的成员注入到 vm 上initInjections(vm) // resolve injections before data/props// 初始化 vm 的 _props/methods/_data/computed/watchinitState(vm)// 初始化 provideinitProvide(vm) // resolve provide after data/props// created 生命钩子的回调callHook(vm, 'created')/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {vm._name = formatComponentName(vm, false)mark(endTag)measure(`vue ${vm._name} init`, startTag, endTag)}if (vm.$options.el) {vm.$mount(vm.$options.el)}}
}
  • initState(vm) 初始化 vm 的 _props/methods/_data/computed/watch
export function initState (vm: Component) {vm._watchers = []const opts = vm.$optionsif (opts.props) initProps(vm, opts.props)if (opts.methods) initMethods(vm, opts.methods)if (opts.data) {initData(vm)} else {observe(vm._data = {}, true /* asRootData */)}if (opts.computed) initComputed(vm, opts.computed)if (opts.watch && opts.watch !== nativeWatch) {initWatch(vm, opts.watch)}
}

7、首次渲染过程——Vue.prototype._init

  • 首次渲染主要流程如下:

    • 1、初始化实例成员:
      • initMixin(Vue)
      • stateMixin(Vue)
      • eventsMixin(Vue)
      • lifecycleMixin(Vue)
      • renderMixin(Vue)
    • 2、初始化静态成员:
      • initGlobalAPI(Vue)
    • 3、调用 _init() 方法:this._init(options) 即 Vue.prototype._init
      • Vue.prototype._init 源码文件见 src/core/instance/init.js
      export function initMixin(Vue: Class < Component > ) {// 给 Vue 实力增加 init() 方法// 合并 options 并且初始化操作Vue.prototype._init = function(options ? : Object) {...// 如果是 Vue 实例不需要被 observevm._isVue = true// merge optionsif (options && options._isComponent) {initInternalComponent(vm, options)} else {vm.$options = mergeOptions(resolveConstructorOptions(vm.constructor),options || {},vm)}/* istanbul ignore else */if (process.env.NODE_ENV !== 'production') {initProxy(vm)} else {vm._renderProxy = vm}// expose real selfvm._self = vm// vm 的生命周期相关变量初始化// $children/$parent/$root/$refsinitLifecycle(vm)// vm 的事件监听初始化,父组件绑定在当前组件上的事件initEvents(vm)// vm 的编译 render 初始化// $slot/$scopedSlots/_c/$createElement/$attrs/$listenrsinitRender(vm)// beforeCreate 生命钩子的回调callHook(vm, 'beforeCreate')// 把 inject 的成员注入到 vm 上initInjections(vm) // resolve injections before data/props// 初始化 vm 的 _props/methods/_data/computed/watchinitState(vm)// 初始化 provideinitProvide(vm) // resolve provide after data/props// created 生命钩子的回调callHook(vm, 'created')...if (vm.$options.el) {// 调用 mount 方法(重点)vm.$mount(vm.$options.el)}}
      }
      
      • vm.$mount (重写 $mount 方法的主要作用就是 compiler template) 方法源码如下,文件见 src/platform/web/entry-runtime-with-compiler.js :
      const mount = Vue.prototype.$mount
      Vue.prototype.$mount = function(el ? : string | Element,// 非 ssr 情况下为 false, ssr 时候为 truehydrating ? : boolean
      ): Component {// 获取 el 对象el = el && query(el)...const options = this.$options// resolve template/el and convert to render functionif (!options.render) {let template = options.templateif (template) {if (typeof template === 'string') {if (template.charAt(0) === '#') {template = idToTemplate(template)/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && !template) {warn(`Template element not found or is empty: ${options.template}`,this)}}} else if (template.nodeType) {template = template.innerHTML} else {if (process.env.NODE_ENV !== 'production') {warn('invalid template option:' + template, this)}return this}} else if (el) {template = getOuterHTML(el)}if (template) {...const { render, staticRenderFns } = compileToFunctions(template, {outputSourceRange: process.env.NODE_ENV !== 'production',shouldDecodeNewlines,shouldDecodeNewlinesForHref,delimiters: options.delimiters,comments: options.comments}, this)options.render = renderoptions.staticRenderFns = staticRenderFns...}}// 调用 mount 方法,渲染 DOMreturn mount.call(this, el, hydrating)
      }
      
      • Vue.prototype.$mount(这个方法在 runtime-with-compiler 的时候会被重写) 方法源码如下,文件见 src/platforms/web/runtime/index.js:
      Vue.prototype.$mount = function(el ? : string | Element,hydrating ? : boolean
      ): Component {el = el && inBrowser ? query(el) : undefinedreturn mountComponent(this, el, hydrating)
      }
      
      • mountComponent 方法源码如下,文件见 src/core/instance/lifecycle.js:
      export function mountComponent (vm: Component,el: ?Element,hydrating?: boolean
      ): Component {vm.$el = elif (!vm.$options.render) {vm.$options.render = createEmptyVNode}callHook(vm, 'beforeMount')let updateComponent/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {updateComponent = () => {const name = vm._nameconst id = vm._uidconst startTag = `vue-perf-start:${id}`const endTag = `vue-perf-end:${id}`mark(startTag)const vnode = vm._render()mark(endTag)measure(`vue ${name} render`, startTag, endTag)mark(startTag)vm._update(vnode, hydrating)mark(endTag)measure(`vue ${name} patch`, startTag, endTag)}} else {updateComponent = () => {vm._update(vm._render(), hydrating)}}new Watcher(vm, updateComponent, noop, {before () {if (vm._isMounted && !vm._isDestroyed) {callHook(vm, 'beforeUpdate')}}}, true /* isRenderWatcher */)hydrating = falseif (vm.$vnode == null) {vm._isMounted = truecallHook(vm, 'mounted')}return vm
      }
      
  • 首次渲染的流程图见:
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PlZHUct4-1596333240775)(…/images/首次渲染过程.png)]

8、数据响应式原理——响应式处理入口

  • 通过查看源码解决下面问题
    • vm.msg = { count: 0 }, 重新给属性赋值,是否是响应式的?
    • vm.arr[0] = 4,给数组元素赋值,试图是否会更新
    • vm.arr.length = 0,修改数组的 length,试图是否会更新
    • vm.arr.push(4),试图是否会更新
  • 响应式处理的入口
    • 整个响应式处理的过程是比较复杂的,下面我们先从入口开始看起
      • src/core/instance/init.js
        • initState(vm) vm状态的初始化
        • 初始化了 _data、_props、methods 等
      • initData(vm): src/core/instance/state.js
      // 数据的初始化
      if (opts.data) {initData(vm)
      } else {observe(vm._data={}, true  /*  asRootData */)
      }
      
      • observe(value: any, asRootData: ? boolean): src/core/observer/index.js
      export function observe(value: any, asRootData: ? boolean): Observer | void {// 判断 value 是否是对象if (!isObject(value) || value instanceof VNode) {return}let ob: Observer | void// 如果 value 有 __ob__(observer 对象) 属性  结束if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {ob = value.__ob__} else if (shouldObserve &&!isServerRendering() &&(Array.isArray(value) || isPlainObject(value)) &&Object.isExtensible(value) &&!value._isVue) {// 创建一个 Observer 对象ob = new Observer(value)}if (asRootData && ob) {ob.vmCount++}return ob
      }
      
      • class Observer: src/core/observer/index.js
      export class Observer {// 观测对象value: any;// 依赖对象dep: Dep;// 实例计数器vmCount: number; // number of vms that have this object as root $dataconstructor(value: any) {this.value = valuethis.dep = new Dep()// 初始化实例的 vmCount 为0this.vmCount = 0// 将实例挂载到观察对象的 __ob__ 属性def(value, '__ob__', this)// 数组的响应式处理if (Array.isArray(value)) {if (hasProto) {protoAugment(value, arrayMethods)} else {copyAugment(value, arrayMethods, arrayKeys)}// 为数组中的每一个对象创建一个 observer 实例this.observeArray(value)} else {// 遍历对象中的每一个属性,转换成 setter/getterthis.walk(value)}}/*** Walk through all properties and convert them into* getter/setters. This method should only be called when* value type is Object.*/walk(obj: Object) {const keys = Object.keys(obj)for (let i = 0; i < keys.length; i++) {defineReactive(obj, keys[i])}}/*** Observe a list of Array items.*/observeArray(items: Array < any > ) {for (let i = 0, l = items.length; i < l; i++) {observe(items[i])}}
      }
      
      • defineReactive (为一个对象定义一个响应式的属性): src/core/observer/index.js
      export function defineReactive(obj: Object,key: string,val: any,customSetter ? : ? Function,shallow ? : boolean
      ) {// 创建依赖对象实例const dep = new Dep()// 获取 obj 的属性描述符对象const property = Object.getOwnPropertyDescriptor(obj, key)if (property && property.configurable === false) {return}// 提供预定义的存取器函数// cater for pre-defined getter/settersconst getter = property && property.getconst setter = property && property.setif ((!getter || setter) && arguments.length === 2) {val = obj[key]}// 判断是否递归观察子对象,并将子对象属性都转换成 getter/setter,返回子观察对象let childOb = !shallow && observe(val)Object.defineProperty(obj, key, {enumerable: true,configurable: true,get: function reactiveGetter() {// 如果预定义的 getter 存在则 value 等于 getter 调用的返回值// 否则直接赋予属性值const value = getter ? getter.call(obj) : val// 如果存在当前依赖目标,即 watcher 对象,则建立依赖if (Dep.target) {dep.depend()// 如果子观察目标存在,建立子对象的依赖关系if (childOb) {childOb.dep.depend()// 如果属性是数组,则特殊处理收集数组对象依赖if (Array.isArray(value)) {dependArray(value)}}}// 返回属性值return value},set: function reactiveSetter(newVal) {// 如果预定义的 getter 存在则 value 等于 getter 调用的返回值// 否则直接赋予属性值const value = getter ? getter.call(obj) : val// 如果新值等于旧值或者新值旧值为 NaN 则不执行/* eslint-disable no-self-compare */if (newVal === value || (newVal !== newVal && value !== value)) {return}/* eslint-enable no-self-compare */if (process.env.NODE_ENV !== 'production' && customSetter) {customSetter()}// 如果没有 setter 直接返回// #7981: for accessor properties without setterif (getter && !setter) return// 如果预定义 setter 存在则调用,否则直接更新新值if (setter) {setter.call(obj, newVal)} else {val = newVal}// 如果新值是对象,观察子对象并返回子对象的 observer 对象childOb = !shallow && observe(newVal)// 派发更新(发布更改通知)dep.notify()}})
      }
      
  • 数据响应式原理——依赖收集
    • defineReactive:入口在 src/core/observer/index.js/defineReactive 函数里
    // 创建依赖对象实例
    const dep = new Dep()
    if (Dep.target) {dep.depend()// 如果子观察目标存在,建立子对象的依赖关系if (childOb) {childOb.dep.depend()// 如果属性是数组,则特殊处理收集数组对象依赖if (Array.isArray(value)) {dependArray(value)}}
    }
    
    • class Dep(创建依赖对象实例):文件在 src/core/observer/dep.js
    export default class Dep {// 静态属性,watcher 对象static target: ? Watcher;// dep 实例 Idid: number;// dep 实例对应的 watcher 对象/订阅者数组subs: Array < Watcher > ;constructor() {this.id = uid++this.subs = []}// 添加新的订阅者 watcher 对象addSub(sub: Watcher) {this.subs.push(sub)}// 移除订阅者removeSub(sub: Watcher) {remove(this.subs, sub)}// 将观察对象和 watcher 建立依赖depend() {if (Dep.target) {// 如果 target 存在,把 dep 对象添加到 watcher 的依赖中Dep.target.addDep(this)}}// 发布通知notify() {// stabilize the subscriber list firstconst subs = this.subs.slice()if (process.env.NODE_ENV !== 'production' && !config.async) {// subs aren't sorted in scheduler if not running async// we need to sort them now to make sure they fire in correct// ordersubs.sort((a, b) => a.id - b.id)}for (let i = 0, l = subs.length; i < l; i++) {subs[i].update()}}
    }
    
    • Dep.target 的 target 的添加逻辑在组件 mount 阶段时 mountComponent 函数里会添加 new Watcher() ,Watcher 类里的 constructor 里会调用 get 方法中的 pushTarget(this)
      • class Watcher:src/core/observer/watcher.js
      export default class Watcher {vm: Component;expression: string;cb: Function;id: number;deep: boolean;user: boolean;lazy: boolean;sync: boolean;dirty: boolean;active: boolean;deps: Array<Dep>;newDeps: Array<Dep>;depIds: SimpleSet;newDepIds: SimpleSet;before: ?Function;getter: Function;value: any;constructor (vm: Component,expOrFn: string | Function,cb: Function,options?: ?Object,isRenderWatcher?: boolean) {this.vm = vmif (isRenderWatcher) {vm._watcher = this}vm._watchers.push(this)// optionsif (options) {this.deep = !!options.deepthis.user = !!options.userthis.lazy = !!options.lazythis.sync = !!options.syncthis.before = options.before} else {this.deep = this.user = this.lazy = this.sync = false}this.cb = cbthis.id = ++uid // uid for batchingthis.active = truethis.dirty = this.lazy // for lazy watchersthis.deps = []this.newDeps = []this.depIds = new Set()this.newDepIds = new Set()this.expression = process.env.NODE_ENV !== 'production'? expOrFn.toString(): ''// parse expression for getterif (typeof expOrFn === 'function') {this.getter = expOrFn} else {this.getter = parsePath(expOrFn)if (!this.getter) {this.getter = noopprocess.env.NODE_ENV !== 'production' && warn(`Failed watching path: "${expOrFn}" ` +'Watcher only accepts simple dot-delimited paths. ' +'For full control, use a function instead.',vm)}}this.value = this.lazy? undefined: this.get()}/*** Evaluate the getter, and re-collect dependencies.*/get () {pushTarget(this)let valueconst vm = this.vmtry {value = this.getter.call(vm, vm)} catch (e) {if (this.user) {handleError(e, vm, `getter for watcher "${this.expression}"`)} else {throw e}} finally {// "touch" every property so they are all tracked as// dependencies for deep watchingif (this.deep) {traverse(value)}popTarget()this.cleanupDeps()}return value}/*** Add a dependency to this directive.*/addDep (dep: Dep) {const id = dep.idif (!this.newDepIds.has(id)) {this.newDepIds.add(id)this.newDeps.push(dep)if (!this.depIds.has(id)) {dep.addSub(this)}}}/*** Clean up for dependency collection.*/cleanupDeps () {let i = this.deps.lengthwhile (i--) {const dep = this.deps[i]if (!this.newDepIds.has(dep.id)) {dep.removeSub(this)}}let tmp = this.depIdsthis.depIds = this.newDepIdsthis.newDepIds = tmpthis.newDepIds.clear()tmp = this.depsthis.deps = this.newDepsthis.newDeps = tmpthis.newDeps.length = 0}/*** Subscriber interface.* Will be called when a dependency changes.*/update () {/* istanbul ignore else */if (this.lazy) {this.dirty = true} else if (this.sync) {this.run()} else {queueWatcher(this)}}/*** Scheduler job interface.* Will be called by the scheduler.*/run () {if (this.active) {const value = this.get()if (value !== this.value ||// Deep watchers and watchers on Object/Arrays should fire even// when the value is the same, because the value may// have mutated.isObject(value) ||this.deep) {// set new valueconst oldValue = this.valuethis.value = valueif (this.user) {try {this.cb.call(this.vm, value, oldValue)} catch (e) {handleError(e, this.vm, `callback for watcher "${this.expression}"`)}} else {this.cb.call(this.vm, value, oldValue)}}}}/*** Evaluate the value of the watcher.* This only gets called for lazy watchers.*/evaluate () {this.value = this.get()this.dirty = false}/*** Depend on all deps collected by this watcher.*/depend () {let i = this.deps.lengthwhile (i--) {this.deps[i].depend()}}/*** Remove self from all dependencies' subscriber list.*/teardown () {if (this.active) {// remove self from vm's watcher list// this is a somewhat expensive operation so we skip it// if the vm is being destroyed.if (!this.vm._isBeingDestroyed) {remove(this.vm._watchers, this)}let i = this.deps.lengthwhile (i--) {this.deps[i].removeSub(this)}this.active = false}}
      }
      
      • pushTarget(将 watcher 挂载到 Dep 的 target 属性下):src/core/observer/dep.js
      // Dep.target 用来存放目前正在使用的 watcher
      // 全局唯一,并且只能有一个 watcher 被使用
      Dep.target = null
      const targetStack = []
      // 入栈并将当前 watcher 赋值给 Dep.target
      export function pushTarget(target: ? Watcher) {targetStack.push(target)Dep.target = target
      }
      
      • dep.depend(收集依赖的过程):src/core/observer/index.js/defineReactive 函数里
      • Dep 类里的 depend 方法源码如下:src/core/observer/dep.js
              // 将观察对象和 watcher 建立依赖depend() {// Dep.target = watcherif (Dep.target) {// 如果 target 存在,把 dep 对象添加到 watcher 的依赖中Dep.target.addDep(this)}}
      
      • Watcher 类里的 addDep 方法源码如下:src/core/observer/watcher.js
      addDep (dep: Dep) {const id = dep.idif (!this.newDepIds.has(id)) {this.newDepIds.add(id)this.newDeps.push(dep)if (!this.depIds.has(id)) {dep.addSub(this)}}
      }
      
      • Dep 类里的 addSub 方法源码如下:src/core/observer/dep.js
      // 添加新的订阅者 watcher 对象
      addSub(sub: Watcher) {this.subs.push(sub)
      }
      
  • 依赖收集的流程图见:https://github.com/smallSix6/fed-e-task-liuhuijun/blob/master/fed-e-task-03-02/note/依赖收集流程.xmind

9、数据响应式原理——数组

  • 数组响应式的入口 class Observer:src/core/observer/index.js
export class Observer {// 观测对象value: any;// 依赖对象dep: Dep;// 实例计数器vmCount: number; // number of vms that have this object as root $dataconstructor(value: any) {this.value = valuethis.dep = new Dep()// 初始化实例的 vmCount 为0this.vmCount = 0// 将实例挂载到观察对象的 __ob__ 属性def(value, '__ob__', this)// 数组的响应式处理if (Array.isArray(value)) {if (hasProto) {protoAugment(value, arrayMethods)} else {copyAugment(value, arrayMethods, arrayKeys)}// 为数组中的每一个对象创建一个 observer 实例this.observeArray(value)} else {// 遍历对象中的每一个属性,转换成 setter/getterthis.walk(value)}}...
}
  • Watcher类
    • Watcher 分为三种,Computed Watcher、用户 Watcher(侦听器)、渲染 Watcher
    • 渲染 Watcher 的创建时机
      • mountComponent:src/core/instance/lifecycle.js
      export function mountComponent (vm: Component,el: ?Element,hydrating?: boolean
      ): Component {vm.$el = el...let updateComponent/* istanbul ignore if */if (process.env.NODE_ENV !== 'production' && config.performance && mark) {...} else {updateComponent = () => {vm._update(vm._render(), hydrating)}}new Watcher(vm, updateComponent, noop, {before () {if (vm._isMounted && !vm._isDestroyed) {callHook(vm, 'beforeUpdate')}}}, true /* isRenderWatcher */)...return vm
      }
      
  • 响应式数组对象发生改变时的流程:
    • dep 的 notify():src/core/observer/dep.js
    // 发布通知
    notify() {// stabilize the subscriber list firstconst subs = this.subs.slice()if (process.env.NODE_ENV !== 'production' && !config.async) {// subs aren't sorted in scheduler if not running async// we need to sort them now to make sure they fire in correct// order// 根据 id 来排序 subsubs.sort((a, b) => a.id - b.id)}// 调用每个订阅者的 update 方法实现更新for (let i = 0, l = subs.length; i < l; i++) {subs[i].update()}
    }
    
    • sub[i].update():c
    update() {/* istanbul ignore else */if (this.lazy) {this.dirty = true} else if (this.sync) {this.run()} else {queueWatcher(this)}
    }
    
    • queueWatcher(this):src/core/observer/scheduler.js
    export function queueWatcher (watcher: Watcher) {const id = watcher.idif (has[id] == null) {has[id] = trueif (!flushing) {queue.push(watcher)} else {// if already flushing, splice the watcher based on its id// if already past its id, it will be run next immediately.let i = queue.length - 1while (i > index && queue[i].id > watcher.id) {i--}queue.splice(i + 1, 0, watcher)}// queue the flushif (!waiting) {waiting = trueif (process.env.NODE_ENV !== 'production' && !config.async) {flushSchedulerQueue()return}nextTick(flushSchedulerQueue)}}
    }
    
    • nextTick(flushSchedulerQueue):src/core/observer/scheduler.js
    • flushSchedulerQueue:src/core/observer/scheduler.js
    function flushSchedulerQueue () {flushing = truelet watcher, id// Sort queue before flush.// This ensures that:// 1. Components are updated from parent to child. (because parent is always//    created before the child)// 2. A component's user watchers are run before its render watcher (because//    user watchers are created before the render watcher)// 3. If a component is destroyed during a parent component's watcher run,//    its watchers can be skipped.queue.sort((a, b) => a.id - b.id)// do not cache length because more watchers might be pushed// as we run existing watchersfor (index = 0; index < queue.length; index++) {watcher = queue[index]if (watcher.before) {watcher.before()}id = watcher.idhas[id] = nullwatcher.run()// in dev build, check and stop circular updates.if (process.env.NODE_ENV !== 'production' && has[id] != null) {circular[id] = (circular[id] || 0) + 1if (circular[id] > MAX_UPDATE_COUNT) {warn('You may have an infinite update loop ' + (watcher.user? `in watcher with expression "${watcher.expression}"`: `in a component render function.`),watcher.vm)break}}}
    
    • watcher.run():src/core/observer/watcher.js
    run() {if (this.active) {const value = this.get()if (value !== this.value ||// Deep watchers and watchers on Object/Arrays should fire even// when the value is the same, because the value may// have mutated.isObject(value) ||this.deep) {// set new valueconst oldValue = this.valuethis.value = valueif (this.user) {try {this.cb.call(this.vm, value, oldValue)} catch (e) {handleError(e, this.vm, `callback for watcher "${this.expression}"`)}} else {this.cb.call(this.vm, value, oldValue)}}}
    }
    
    • this.get() 即 watcher 的 get 方法,触发收集依赖和更新

10、set——源码

  • 定义位置
    • Vue.set()
      • src/core/global-api/index.js
      Vue.set = set
      Vue.delete = del
      Vue.nextTick = nextTick
      
    • vm.$set()
      • src/core/instance/index.js
          // 注册 vm 的 $data/$props/$set/$delete/$watch
      stateMixin(Vue)
      
      • src/core/instance/state.js
      Vue.prototype.$set = set
      Vue.prototype.$delete = del
      
  • set():src/core/observer/index.js
export function set(target: Array < any > | Object, key: any, val: any): any {if (process.env.NODE_ENV !== 'production' &&(isUndef(target) || isPrimitive(target))) {warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)}// 判断 target 是否是对象,key 是否是合法的索引if (Array.isArray(target) && isValidArrayIndex(key)) {target.length = Math.max(target.length, key)// 通过 splice 对 key 位置的元素进行替换// splice 在 array.js 进行了响应式的处理target.splice(key, 1, val)return val}// 如果 key 在对象中已经存在直接赋值if (key in target && !(key in Object.prototype)) {target[key] = valreturn val}// 获取 target 中的 observer 对象const ob = (target: any).__ob__// 如果 target 是 vue 实例或者 $data 直接返回if (target._isVue || (ob && ob.vmCount)) {process.env.NODE_ENV !== 'production' && warn('Avoid adding reactive properties to a Vue instance or its root $data ' +'at runtime - declare it upfront in the data option.')return val}// 如果 ob 不存在,target 不是响应式对象,则不添加响应式的处理并直接赋值if (!ob) {target[key] = valreturn val}// 把 key 设置为响应式属性defineReactive(ob.value, key, val)// 发送通知ob.dep.notify()return val
}

11、delete——源码

  • vm.$delete
    • 功能:删除对象的属性。如果对象是响应式的,确保删除能触发更新视图。这个方法主要用于避开 Vue 不能检测到属性被删除的限制,但是你应该很少会使用它。
      • 注意:目标对象不能是一个 Vue 实例或 Vue 实例的根数据对象。
    • 示例:
    vm.$delete(vm.obj, 'msg')
    
  • 定义位置
    • Vue.delete: src/core/global-api/index.js
    • delete():src/core/observer/index.js
    export function del(target: Array < any > | Object, key: any) {if (process.env.NODE_ENV !== 'production' &&(isUndef(target) || isPrimitive(target))) {warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target: any)}`)}// 判断是否是数组,以及 key 是否合法if (Array.isArray(target) && isValidArrayIndex(key)) {// 如果是数组通过 splice 删除// splice 做过响应式处理target.splice(key, 1)return}// 获取 target 的 ob 对象const ob = (target: any).__ob__// 如果 target 是 vue 实例或者 $data 直接返回if (target._isVue || (ob && ob.vmCount)) {process.env.NODE_ENV !== 'production' && warn('Avoid deleting properties on a Vue instance or its root $data ' +'- just set it to null.')return}// 如果 target 对象没有 key 属性直接返回if (!hasOwn(target, key)) {return}// 删除属性delete target[key]if (!ob) {return}// 发送通知ob.dep.notify()
    }
    

12、watch——回顾

  • vm.$watch(expOrFn, callback, [options])
    • 功能:观察 Vue 实例变化的一个表达式或计算属性函数,回调函数得到的参数为新值和旧值。表达式只接受监督的键路径。对于更复杂的表达式,用一个函数取代

    • 参数:

      • expOrFn:要监视的 $data 中的属性,可以是表达式或函数
      • callback:数据变化后执行函数
        • 函数:回调函数
        • 对象:具有 handler 属性(字符串或者函数),如果该属性为字符串则 methods 中相应的定义
      • options:可选的选项
        • deep:布尔类型,深度监听
        • immediate:布尔类型,是否立即执行一次回调函数
    • 示例:

    var vm = new Vue({data: {a: 1,b: 2,c: 3,d: 4,e: {f: {g: 5}}},watch: {a: function (val, oldVal) {console.log('new: %s, old: %s', val, oldVal)},// 方法名b: 'someMethod',// 该回调会在任何被侦听的对象的 property 改变时被调用,不论其被嵌套多深c: {handler: function (val, oldVal) { /* ... */ },deep: true},// 该回调将会在侦听开始之后被立即调用d: {handler: 'someMethod',immediate: true},// 你可以传入回调数组,它们会被逐一调用e: ['handle1',function handle2 (val, oldVal) { /* ... */ },{handler: function handle3 (val, oldVal) { /* ... */ },/* ... */}],// watch vm.e.f's value: {g: 5}'e.f': function (val, oldVal) { /* ... */ }}
    })
    vm.a = 2 // => new: 2, old: 1
    
    • 三种类型的 Watcher 对象
      • 没有静态方法,因为 $watch 方法中要使用 Vue 的实例
      • Watcher 分三种:计算属性 Watcher、用户 Watche(侦听器)、渲染 Watcher
        • 创建顺序:计算属性 Watcher、用户 Watcher(侦听器)、渲染 Watcher
      • vm.$watche()
        • src/core/instance/state.js

13、watche——源码

  • initState(vm: Component):src/core/instance/state.js
export function initState (vm: Component) {vm._watchers = []const opts = vm.$optionsif (opts.props) initProps(vm, opts.props)if (opts.methods) initMethods(vm, opts.methods)if (opts.data) {initData(vm)} else {observe(vm._data = {}, true /* asRootData */)}if (opts.computed) initComputed(vm, opts.computed)if (opts.watch && opts.watch !== nativeWatch) {initWatch(vm, opts.watch)}
}
  • initWatch (vm: Component, watch: Object:src/core/instance/state.js
function initWatch (vm: Component, watch: Object) {for (const key in watch) {const handler = watch[key]if (Array.isArray(handler)) {for (let i = 0; i < handler.length; i++) {createWatcher(vm, key, handler[i])}} else {createWatcher(vm, key, handler)}}
}
  • createWatcher (vm: Component, expOrFn: string | Function, handler: any, options?: Object):src/core/instance/state.js
function createWatcher (vm: Component,expOrFn: string | Function,handler: any,options?: Object
) {if (isPlainObject(handler)) {options = handlerhandler = handler.handler}if (typeof handler === 'string') {handler = vm[handler]}return vm.$watch(expOrFn, handler, options)
}
  • vm.$watch(expOrFn, handler, options):src/core/instance/state.js
Vue.prototype.$watch = function(expOrFn: string | Function,cb: any,options ? : Object
): Function {// 获取 Vue 实例 thisconst vm: Component = thisif (isPlainObject(cb)) {// 判断如果 cb 是对象,执行 createWatcher return createWatcher(vm, expOrFn, cb, options)}options = options || {}// 标记为用户 watcheroptions.user = true// 创建用户 watcher 对象const watcher = new Watcher(vm, expOrFn, cb, options)// 判断 immediate 如果为 trueif (options.immediate) {// 立即执行一次 cb 回调,并且把当前值传入try {cb.call(vm, watcher.value)} catch (error) {handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)}}// 返回取消监听的方法return function unwatchFn() {watcher.teardown()}
}

14、nextTick——源码

  • 异步更新队列——nextTick()
    • Vue 更新 DOM 是异步执行的,批量的
      • 在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后立即使用这个方法,获得更新后的 DOM
    • vm.$nextTick(function(){/* 操作DOM */}) / Vue.nextTick(function(){})
  • vm.$nextTick 代码演示
<div id="app"><p ref='p1'>{{msg}}</p>
</div><script src="../../dist/vue.js"></script>
<script>const vm = new Vue({el: '#app',data: {msg: 'Hello nextTick',name: 'Vue.js',title: 'Title'},mounted() {this.msg = 'Hello World'this.name = 'Hello snambdom'this.title = 'Vue.js'this.$nextTick(() => {console.log(this.$refs.p1.textContent)})}})
</script>
  • 源码
    • 定义位置
      • src/core/instance/render.js
      Vue.prototype.$nextTick = function(fn: Function) {return nextTick(fn, this)
      }
      
    • 流程:
      • 手动调用 vm.$nextTick()
      • 在 Watcher 的 queueWatcher 中执行 nextTick()
      • src/core/util/next-tick.js
      export function nextTick(cb? : Function, ctx? : Object) {let _resolve// 把 cb 加上异常处理存入 callbacks 数组中callbacks.push(() => {if (cb) {try {// 调用 cb()cb.call(ctx)} catch (e) {handleError(e, ctx, 'nextTick')}} else if (_resolve) {_resolve(ctx)}})if (!pending) {pending = true// 调用timerFunc()}// $flow-disable-lineif (!cb && typeof Promise !== 'undefined') {// 返回 promise 对象return new Promise(resolve => {_resolve = resolve})}
      }
      
查看全文
如若内容造成侵权/违法违规/事实不符,请联系编程学习网邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

相关文章

  1. 微创双眼皮缺点

    ...

    2024/4/27 8:23:35
  2. Maven 快速生成Java项目结构

    Maven使用 archetype 来创建项目。要创建一个简单的 Java 应用程序&#xff0c;我们使用 maven-archetype-quickstart 插件。在下面的例子中&#xff0c;我们将创建一个基于Maven 的 Java 应用程序项目在 G:\workspace 文件夹。 让我们打开命令控制台&#xff0c;进入到 G:\wo…...

    2024/4/21 6:35:55
  3. 基于Angularjs实现分页

    前言 学习任何一门语言前肯定是有业务需求来驱动你去学习它&#xff0c;当然ng也不例外&#xff0c;在学习ng前我第一个想做的demo就是基于ng实现分页&#xff0c;除去基本的计算思路外就是使用指令封装成一个插件&#xff0c;在需要分页的列表页面内直接引用。 插件 在封装分页…...

    2024/4/20 19:04:28
  4. 浅谈Django的Q查询以及AngularJS的Datatables分页插件

    使用Q查询&#xff0c;首先要导入Q模块&#xff1a; from django.db.models import Q 可以组合使用&,|操作符用于多个Q的对象,产生一个新的Q对象&#xff0c;Q对象也可以用~操作符放在前面表示否定&#xff0c;如下例所示&#xff1a; if search:keywords_list search.spl…...

    2024/4/19 23:04:40
  5. 双眼皮疤痕膏

    ...

    2024/4/28 7:03:47
  6. requireJS-build.js

    源文件地址&#xff1a;https://github.com/requirejs/r.js/blob/master/build/example.build.js /** 这是一个示例build文件,用来示范如何为requireJs应用build system* 这个build文件不是有效的&#xff0c;它所引用的路径在你的机器中可能不存在&#xff0c;该文件仅仅作为学…...

    2024/4/20 19:04:25
  7. angularjs的懒加载

    1、angularJS懒加载依赖模块 //设置 .config [ $ocLazyLoadProvider ($ocLazyLoadProvider) -> # We configure ocLazyLoad to use the lib script.js as the async loader $ocLazyLoadProvider.config debug: true events: true modules: [ { name: ui.grid files: [ //cdn…...

    2024/4/28 7:34:29
  8. r.js 合并require.js 引入文件 uglifyjs压缩代码

    2019独角兽企业重金招聘Python工程师标准>>> build.js 已经写好&#xff0c;直接运行命令&#xff0c;然后看报错哪个没引入&#xff0c;然后直接引入。再运行。 http://www.zhangxinxu.com/wordpress/2013/01/uglifyjs-compress-js/ 压缩 uglifyjs inet.js -m -o …...

    2024/4/21 6:35:53
  9. 疤痕体质可以割双眼皮吗

    ...

    2024/4/20 6:37:43
  10. Require.js的基本用法详解

    一:什么是require.js ①&#xff1a;require.js是一个js脚本加载器&#xff0c;它遵循AMD(Asynchronous Module Definition)规范&#xff0c;实现js脚本的异步加载&#xff0c;不阻塞页面的渲染和其后的脚本的执行&#xff0c;并提供了在加载完成之后的执行相应回调函数的功能&…...

    2024/4/21 6:35:51
  11. require.js

    一:什么是require.js ①&#xff1a;require.js是一个js脚本加载器&#xff0c;它遵循AMD(Asynchronous Module Definition)规范&#xff0c;实现js脚本的异步加载&#xff0c;不阻塞页面的渲染和其后的脚本的执行&#xff0c;并提供了在加载完成之后的执行相应回调函数的功能&…...

    2024/4/21 6:35:50
  12. 双眼皮贴闭眼

    ...

    2024/4/21 6:35:50
  13. 前端知识点总结---面试专用

    1.关于基础css html js部分 1.1基本算法 1&#xff09;快速排序 时间复杂度 nlogn function quickSort(arr){if (arr.length<1){return arr;}var pivotIndex 0,pivort arr.splice(pivortIndex, 1)[0];var left [],right [];for (var i 1, length arr.length; i < l…...

    2024/4/20 7:53:12
  14. Web前端代码构建优化

    前言 本次所做的构建针对于iVMS-5200 Professional 车载 1.0项目的前端工程。在现在化Web开发情况下&#xff0c;越来越注重用户体验&#xff0c;具体包括网站的访问速度&#xff0c;页面的自适应&#xff0c;页面操作的流畅度。如何做到更快&#xff0c;对前端开发人员尤为重…...

    2024/4/24 8:54:43
  15. Keil : Error-Flash Download failed Cortex-M4错误解决方案整理(J-Flash擦除下载教程)

    Keil : Error-Flash Download failed Cortex-M4错误解决方案整理在开发 nRF51822/nRF52832/nRF52840时候出现如下如下问题:问题: Keil电子下载时候出现 Error: Flash Download failed - "Cortex-M4"的错误,如下图根据官方教程解释如下,还是发现不容易解决,另外结…...

    2024/4/21 6:35:46
  16. require.js的好处以及用法(三)

    require.config({    urlArgs: "v" new Date().getTime(),baseUrl: "./js",paths: {      jquery1:["//cdn.bootcss.com/jquery/1.11.1/jquery","lib/jquery-1.11.1"],//数组&#xff0c;如果前面没有的话就加载后面的。jq…...

    2024/4/21 6:35:45
  17. Vue computed以及watch简单实现

    Vue computed以及watch简单实现Vue computed以及watch简单实现需求&#xff0c;实际应用场景说明结果展示代码中一些对象属性的概念解释上原理图描述一下响应式过程属性响应式初始化Dep与Watcher在响应式初始化的作用计算属性监听属性最后附上完整html可执行代码Vue computed以…...

    2024/4/29 17:04:22
  18. 双眼皮发青肿

    ...

    2024/4/21 6:35:43
  19. 前端模块化小总结—commonJs,AMD,CMD, ES6 的Module

    随着前端快速发展&#xff0c;需要使用javascript处理越来越多的事情&#xff0c;不在局限页面的交互&#xff0c;项目的需求越来越多&#xff0c;更多的逻辑需要在前端完成&#xff0c;这时需要一种新的模式 --模块化编程 模块化的理解&#xff1a;模块化是一种处理复杂系统分…...

    2024/4/21 6:35:42
  20. 合肥105整容上睑下垂做双眼皮怎么割

    ...

    2024/4/21 6:35:42

最新文章

  1. 【SQL】根据条件分组,并根据条件取最大的这一条数据

    数据&#xff0c;当字段A相同时&#xff0c;取字段B数值大的这一条数据 ABC123114223234 期望结果 ABC123234 Oracle SELECT A, B, C FROM (SELECT A, B, C,ROW_NUMBER() OVER (PARTITION BY A ORDER BY B DESC) AS rnFROM 表名 ) WHERE rn 1; MySql SELECT t1.A, t1.B,…...

    2024/5/1 11:51:27
  2. 梯度消失和梯度爆炸的一些处理方法

    在这里是记录一下梯度消失或梯度爆炸的一些处理技巧。全当学习总结了如有错误还请留言&#xff0c;在此感激不尽。 权重和梯度的更新公式如下&#xff1a; w w − η ⋅ ∇ w w w - \eta \cdot \nabla w ww−η⋅∇w 个人通俗的理解梯度消失就是网络模型在反向求导的时候出…...

    2024/3/20 10:50:27
  3. 第十三届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组 题解

    VP比赛链接 : 数据加载中... - 蓝桥云课 1 . 九进制 转 十进制 直接模拟就好了 #include <iostream> using namespace std; int main() {// 请在此输入您的代码int x 22*92*81*9;cout << x << endl ;return 0; } 2 . 顺子日期 枚举出每个情况即可 : …...

    2024/4/30 1:59:34
  4. 前端 js 经典:字符编码详解

    前言&#xff1a;计算机只能识别二进制&#xff0c;开发语言中数据类型还有数字&#xff0c;字母&#xff0c;中文&#xff0c;特殊符号等&#xff0c;都需要转化成二进制编码才能让技术机识别。 一. 编码方式 ACSLL、Unicode、utf-8、URL 编码、base64 等。 1. ACSLL 对英语…...

    2024/4/29 3:52:58
  5. 【外汇早评】美通胀数据走低,美元调整

    原标题:【外汇早评】美通胀数据走低,美元调整昨日美国方面公布了新一期的核心PCE物价指数数据,同比增长1.6%,低于前值和预期值的1.7%,距离美联储的通胀目标2%继续走低,通胀压力较低,且此前美国一季度GDP初值中的消费部分下滑明显,因此市场对美联储后续更可能降息的政策…...

    2024/4/29 23:16:47
  6. 【原油贵金属周评】原油多头拥挤,价格调整

    原标题:【原油贵金属周评】原油多头拥挤,价格调整本周国际劳动节,我们喜迎四天假期,但是整个金融市场确实流动性充沛,大事频发,各个商品波动剧烈。美国方面,在本周四凌晨公布5月份的利率决议和新闻发布会,维持联邦基金利率在2.25%-2.50%不变,符合市场预期。同时美联储…...

    2024/4/30 18:14:14
  7. 【外汇周评】靓丽非农不及疲软通胀影响

    原标题:【外汇周评】靓丽非农不及疲软通胀影响在刚结束的周五,美国方面公布了新一期的非农就业数据,大幅好于前值和预期,新增就业重新回到20万以上。具体数据: 美国4月非农就业人口变动 26.3万人,预期 19万人,前值 19.6万人。 美国4月失业率 3.6%,预期 3.8%,前值 3…...

    2024/4/29 2:29:43
  8. 【原油贵金属早评】库存继续增加,油价收跌

    原标题:【原油贵金属早评】库存继续增加,油价收跌周三清晨公布美国当周API原油库存数据,上周原油库存增加281万桶至4.692亿桶,增幅超过预期的74.4万桶。且有消息人士称,沙特阿美据悉将于6月向亚洲炼油厂额外出售更多原油,印度炼油商预计将每日获得至多20万桶的额外原油供…...

    2024/4/30 18:21:48
  9. 【外汇早评】日本央行会议纪要不改日元强势

    原标题:【外汇早评】日本央行会议纪要不改日元强势近两日日元大幅走强与近期市场风险情绪上升,避险资金回流日元有关,也与前一段时间的美日贸易谈判给日本缓冲期,日本方面对汇率问题也避免继续贬值有关。虽然今日早间日本央行公布的利率会议纪要仍然是支持宽松政策,但这符…...

    2024/4/27 17:58:04
  10. 【原油贵金属早评】欧佩克稳定市场,填补伊朗问题的影响

    原标题:【原油贵金属早评】欧佩克稳定市场,填补伊朗问题的影响近日伊朗局势升温,导致市场担忧影响原油供给,油价试图反弹。此时OPEC表态稳定市场。据消息人士透露,沙特6月石油出口料将低于700万桶/日,沙特已经收到石油消费国提出的6月份扩大出口的“适度要求”,沙特将满…...

    2024/4/27 14:22:49
  11. 【外汇早评】美欲与伊朗重谈协议

    原标题:【外汇早评】美欲与伊朗重谈协议美国对伊朗的制裁遭到伊朗的抗议,昨日伊朗方面提出将部分退出伊核协议。而此行为又遭到欧洲方面对伊朗的谴责和警告,伊朗外长昨日回应称,欧洲国家履行它们的义务,伊核协议就能保证存续。据传闻伊朗的导弹已经对准了以色列和美国的航…...

    2024/4/28 1:28:33
  12. 【原油贵金属早评】波动率飙升,市场情绪动荡

    原标题:【原油贵金属早评】波动率飙升,市场情绪动荡因中美贸易谈判不安情绪影响,金融市场各资产品种出现明显的波动。随着美国与中方开启第十一轮谈判之际,美国按照既定计划向中国2000亿商品征收25%的关税,市场情绪有所平复,已经开始接受这一事实。虽然波动率-恐慌指数VI…...

    2024/4/30 9:43:09
  13. 【原油贵金属周评】伊朗局势升温,黄金多头跃跃欲试

    原标题:【原油贵金属周评】伊朗局势升温,黄金多头跃跃欲试美国和伊朗的局势继续升温,市场风险情绪上升,避险黄金有向上突破阻力的迹象。原油方面稍显平稳,近期美国和OPEC加大供给及市场需求回落的影响,伊朗局势并未推升油价走强。近期中美贸易谈判摩擦再度升级,美国对中…...

    2024/4/27 17:59:30
  14. 【原油贵金属早评】市场情绪继续恶化,黄金上破

    原标题:【原油贵金属早评】市场情绪继续恶化,黄金上破周初中国针对于美国加征关税的进行的反制措施引发市场情绪的大幅波动,人民币汇率出现大幅的贬值动能,金融市场受到非常明显的冲击。尤其是波动率起来之后,对于股市的表现尤其不安。隔夜美国股市出现明显的下行走势,这…...

    2024/4/25 18:39:16
  15. 【外汇早评】美伊僵持,风险情绪继续升温

    原标题:【外汇早评】美伊僵持,风险情绪继续升温昨日沙特两艘油轮再次发生爆炸事件,导致波斯湾局势进一步恶化,市场担忧美伊可能会出现摩擦生火,避险品种获得支撑,黄金和日元大幅走强。美指受中美贸易问题影响而在低位震荡。继5月12日,四艘商船在阿联酋领海附近的阿曼湾、…...

    2024/4/28 1:34:08
  16. 【原油贵金属早评】贸易冲突导致需求低迷,油价弱势

    原标题:【原油贵金属早评】贸易冲突导致需求低迷,油价弱势近日虽然伊朗局势升温,中东地区几起油船被袭击事件影响,但油价并未走高,而是出于调整结构中。由于市场预期局势失控的可能性较低,而中美贸易问题导致的全球经济衰退风险更大,需求会持续低迷,因此油价调整压力较…...

    2024/4/26 19:03:37
  17. 氧生福地 玩美北湖(上)——为时光守候两千年

    原标题:氧生福地 玩美北湖(上)——为时光守候两千年一次说走就走的旅行,只有一张高铁票的距离~ 所以,湖南郴州,我来了~ 从广州南站出发,一个半小时就到达郴州西站了。在动车上,同时改票的南风兄和我居然被分到了一个车厢,所以一路非常愉快地聊了过来。 挺好,最起…...

    2024/4/29 20:46:55
  18. 氧生福地 玩美北湖(中)——永春梯田里的美与鲜

    原标题:氧生福地 玩美北湖(中)——永春梯田里的美与鲜一觉醒来,因为大家太爱“美”照,在柳毅山庄去寻找龙女而错过了早餐时间。近十点,向导坏坏还是带着饥肠辘辘的我们去吃郴州最富有盛名的“鱼头粉”。说这是“十二分推荐”,到郴州必吃的美食之一。 哇塞!那个味美香甜…...

    2024/4/30 22:21:04
  19. 氧生福地 玩美北湖(下)——奔跑吧骚年!

    原标题:氧生福地 玩美北湖(下)——奔跑吧骚年!让我们红尘做伴 活得潇潇洒洒 策马奔腾共享人世繁华 对酒当歌唱出心中喜悦 轰轰烈烈把握青春年华 让我们红尘做伴 活得潇潇洒洒 策马奔腾共享人世繁华 对酒当歌唱出心中喜悦 轰轰烈烈把握青春年华 啊……啊……啊 两…...

    2024/5/1 4:32:01
  20. 扒开伪装医用面膜,翻六倍价格宰客,小姐姐注意了!

    原标题:扒开伪装医用面膜,翻六倍价格宰客,小姐姐注意了!扒开伪装医用面膜,翻六倍价格宰客!当行业里的某一品项火爆了,就会有很多商家蹭热度,装逼忽悠,最近火爆朋友圈的医用面膜,被沾上了污点,到底怎么回事呢? “比普通面膜安全、效果好!痘痘、痘印、敏感肌都能用…...

    2024/4/27 23:24:42
  21. 「发现」铁皮石斛仙草之神奇功效用于医用面膜

    原标题:「发现」铁皮石斛仙草之神奇功效用于医用面膜丽彦妆铁皮石斛医用面膜|石斛多糖无菌修护补水贴19大优势: 1、铁皮石斛:自唐宋以来,一直被列为皇室贡品,铁皮石斛生于海拔1600米的悬崖峭壁之上,繁殖力差,产量极低,所以古代仅供皇室、贵族享用 2、铁皮石斛自古民间…...

    2024/4/28 5:48:52
  22. 丽彦妆\医用面膜\冷敷贴轻奢医学护肤引导者

    原标题:丽彦妆\医用面膜\冷敷贴轻奢医学护肤引导者【公司简介】 广州华彬企业隶属香港华彬集团有限公司,专注美业21年,其旗下品牌: 「圣茵美」私密荷尔蒙抗衰,产后修复 「圣仪轩」私密荷尔蒙抗衰,产后修复 「花茵莳」私密荷尔蒙抗衰,产后修复 「丽彦妆」专注医学护…...

    2024/4/30 9:42:22
  23. 广州械字号面膜生产厂家OEM/ODM4项须知!

    原标题:广州械字号面膜生产厂家OEM/ODM4项须知!广州械字号面膜生产厂家OEM/ODM流程及注意事项解读: 械字号医用面膜,其实在我国并没有严格的定义,通常我们说的医美面膜指的应该是一种「医用敷料」,也就是说,医用面膜其实算作「医疗器械」的一种,又称「医用冷敷贴」。 …...

    2024/4/30 9:43:22
  24. 械字号医用眼膜缓解用眼过度到底有无作用?

    原标题:械字号医用眼膜缓解用眼过度到底有无作用?医用眼膜/械字号眼膜/医用冷敷眼贴 凝胶层为亲水高分子材料,含70%以上的水分。体表皮肤温度传导到本产品的凝胶层,热量被凝胶内水分子吸收,通过水分的蒸发带走大量的热量,可迅速地降低体表皮肤局部温度,减轻局部皮肤的灼…...

    2024/4/30 9:42:49
  25. 配置失败还原请勿关闭计算机,电脑开机屏幕上面显示,配置失败还原更改 请勿关闭计算机 开不了机 这个问题怎么办...

    解析如下&#xff1a;1、长按电脑电源键直至关机&#xff0c;然后再按一次电源健重启电脑&#xff0c;按F8健进入安全模式2、安全模式下进入Windows系统桌面后&#xff0c;按住“winR”打开运行窗口&#xff0c;输入“services.msc”打开服务设置3、在服务界面&#xff0c;选中…...

    2022/11/19 21:17:18
  26. 错误使用 reshape要执行 RESHAPE,请勿更改元素数目。

    %读入6幅图像&#xff08;每一幅图像的大小是564*564&#xff09; f1 imread(WashingtonDC_Band1_564.tif); subplot(3,2,1),imshow(f1); f2 imread(WashingtonDC_Band2_564.tif); subplot(3,2,2),imshow(f2); f3 imread(WashingtonDC_Band3_564.tif); subplot(3,2,3),imsho…...

    2022/11/19 21:17:16
  27. 配置 已完成 请勿关闭计算机,win7系统关机提示“配置Windows Update已完成30%请勿关闭计算机...

    win7系统关机提示“配置Windows Update已完成30%请勿关闭计算机”问题的解决方法在win7系统关机时如果有升级系统的或者其他需要会直接进入一个 等待界面&#xff0c;在等待界面中我们需要等待操作结束才能关机&#xff0c;虽然这比较麻烦&#xff0c;但是对系统进行配置和升级…...

    2022/11/19 21:17:15
  28. 台式电脑显示配置100%请勿关闭计算机,“准备配置windows 请勿关闭计算机”的解决方法...

    有不少用户在重装Win7系统或更新系统后会遇到“准备配置windows&#xff0c;请勿关闭计算机”的提示&#xff0c;要过很久才能进入系统&#xff0c;有的用户甚至几个小时也无法进入&#xff0c;下面就教大家这个问题的解决方法。第一种方法&#xff1a;我们首先在左下角的“开始…...

    2022/11/19 21:17:14
  29. win7 正在配置 请勿关闭计算机,怎么办Win7开机显示正在配置Windows Update请勿关机...

    置信有很多用户都跟小编一样遇到过这样的问题&#xff0c;电脑时发现开机屏幕显现“正在配置Windows Update&#xff0c;请勿关机”(如下图所示)&#xff0c;而且还需求等大约5分钟才干进入系统。这是怎样回事呢&#xff1f;一切都是正常操作的&#xff0c;为什么开时机呈现“正…...

    2022/11/19 21:17:13
  30. 准备配置windows 请勿关闭计算机 蓝屏,Win7开机总是出现提示“配置Windows请勿关机”...

    Win7系统开机启动时总是出现“配置Windows请勿关机”的提示&#xff0c;没过几秒后电脑自动重启&#xff0c;每次开机都这样无法进入系统&#xff0c;此时碰到这种现象的用户就可以使用以下5种方法解决问题。方法一&#xff1a;开机按下F8&#xff0c;在出现的Windows高级启动选…...

    2022/11/19 21:17:12
  31. 准备windows请勿关闭计算机要多久,windows10系统提示正在准备windows请勿关闭计算机怎么办...

    有不少windows10系统用户反映说碰到这样一个情况&#xff0c;就是电脑提示正在准备windows请勿关闭计算机&#xff0c;碰到这样的问题该怎么解决呢&#xff0c;现在小编就给大家分享一下windows10系统提示正在准备windows请勿关闭计算机的具体第一种方法&#xff1a;1、2、依次…...

    2022/11/19 21:17:11
  32. 配置 已完成 请勿关闭计算机,win7系统关机提示“配置Windows Update已完成30%请勿关闭计算机”的解决方法...

    今天和大家分享一下win7系统重装了Win7旗舰版系统后&#xff0c;每次关机的时候桌面上都会显示一个“配置Windows Update的界面&#xff0c;提示请勿关闭计算机”&#xff0c;每次停留好几分钟才能正常关机&#xff0c;导致什么情况引起的呢&#xff1f;出现配置Windows Update…...

    2022/11/19 21:17:10
  33. 电脑桌面一直是清理请关闭计算机,windows7一直卡在清理 请勿关闭计算机-win7清理请勿关机,win7配置更新35%不动...

    只能是等着&#xff0c;别无他法。说是卡着如果你看硬盘灯应该在读写。如果从 Win 10 无法正常回滚&#xff0c;只能是考虑备份数据后重装系统了。解决来方案一&#xff1a;管理员运行cmd&#xff1a;net stop WuAuServcd %windir%ren SoftwareDistribution SDoldnet start WuA…...

    2022/11/19 21:17:09
  34. 计算机配置更新不起,电脑提示“配置Windows Update请勿关闭计算机”怎么办?

    原标题&#xff1a;电脑提示“配置Windows Update请勿关闭计算机”怎么办&#xff1f;win7系统中在开机与关闭的时候总是显示“配置windows update请勿关闭计算机”相信有不少朋友都曾遇到过一次两次还能忍但经常遇到就叫人感到心烦了遇到这种问题怎么办呢&#xff1f;一般的方…...

    2022/11/19 21:17:08
  35. 计算机正在配置无法关机,关机提示 windows7 正在配置windows 请勿关闭计算机 ,然后等了一晚上也没有关掉。现在电脑无法正常关机...

    关机提示 windows7 正在配置windows 请勿关闭计算机 &#xff0c;然后等了一晚上也没有关掉。现在电脑无法正常关机以下文字资料是由(历史新知网www.lishixinzhi.com)小编为大家搜集整理后发布的内容&#xff0c;让我们赶快一起来看一下吧&#xff01;关机提示 windows7 正在配…...

    2022/11/19 21:17:05
  36. 钉钉提示请勿通过开发者调试模式_钉钉请勿通过开发者调试模式是真的吗好不好用...

    钉钉请勿通过开发者调试模式是真的吗好不好用 更新时间:2020-04-20 22:24:19 浏览次数:729次 区域: 南阳 > 卧龙 列举网提醒您:为保障您的权益,请不要提前支付任何费用! 虚拟位置外设器!!轨迹模拟&虚拟位置外设神器 专业用于:钉钉,外勤365,红圈通,企业微信和…...

    2022/11/19 21:17:05
  37. 配置失败还原请勿关闭计算机怎么办,win7系统出现“配置windows update失败 还原更改 请勿关闭计算机”,长时间没反应,无法进入系统的解决方案...

    前几天班里有位学生电脑(windows 7系统)出问题了&#xff0c;具体表现是开机时一直停留在“配置windows update失败 还原更改 请勿关闭计算机”这个界面&#xff0c;长时间没反应&#xff0c;无法进入系统。这个问题原来帮其他同学也解决过&#xff0c;网上搜了不少资料&#x…...

    2022/11/19 21:17:04
  38. 一个电脑无法关闭计算机你应该怎么办,电脑显示“清理请勿关闭计算机”怎么办?...

    本文为你提供了3个有效解决电脑显示“清理请勿关闭计算机”问题的方法&#xff0c;并在最后教给你1种保护系统安全的好方法&#xff0c;一起来看看&#xff01;电脑出现“清理请勿关闭计算机”在Windows 7(SP1)和Windows Server 2008 R2 SP1中&#xff0c;添加了1个新功能在“磁…...

    2022/11/19 21:17:03
  39. 请勿关闭计算机还原更改要多久,电脑显示:配置windows更新失败,正在还原更改,请勿关闭计算机怎么办...

    许多用户在长期不使用电脑的时候&#xff0c;开启电脑发现电脑显示&#xff1a;配置windows更新失败&#xff0c;正在还原更改&#xff0c;请勿关闭计算机。。.这要怎么办呢&#xff1f;下面小编就带着大家一起看看吧&#xff01;如果能够正常进入系统&#xff0c;建议您暂时移…...

    2022/11/19 21:17:02
  40. 还原更改请勿关闭计算机 要多久,配置windows update失败 还原更改 请勿关闭计算机,电脑开机后一直显示以...

    配置windows update失败 还原更改 请勿关闭计算机&#xff0c;电脑开机后一直显示以以下文字资料是由(历史新知网www.lishixinzhi.com)小编为大家搜集整理后发布的内容&#xff0c;让我们赶快一起来看一下吧&#xff01;配置windows update失败 还原更改 请勿关闭计算机&#x…...

    2022/11/19 21:17:01
  41. 电脑配置中请勿关闭计算机怎么办,准备配置windows请勿关闭计算机一直显示怎么办【图解】...

    不知道大家有没有遇到过这样的一个问题&#xff0c;就是我们的win7系统在关机的时候&#xff0c;总是喜欢显示“准备配置windows&#xff0c;请勿关机”这样的一个页面&#xff0c;没有什么大碍&#xff0c;但是如果一直等着的话就要两个小时甚至更久都关不了机&#xff0c;非常…...

    2022/11/19 21:17:00
  42. 正在准备配置请勿关闭计算机,正在准备配置windows请勿关闭计算机时间长了解决教程...

    当电脑出现正在准备配置windows请勿关闭计算机时&#xff0c;一般是您正对windows进行升级&#xff0c;但是这个要是长时间没有反应&#xff0c;我们不能再傻等下去了。可能是电脑出了别的问题了&#xff0c;来看看教程的说法。正在准备配置windows请勿关闭计算机时间长了方法一…...

    2022/11/19 21:16:59
  43. 配置失败还原请勿关闭计算机,配置Windows Update失败,还原更改请勿关闭计算机...

    我们使用电脑的过程中有时会遇到这种情况&#xff0c;当我们打开电脑之后&#xff0c;发现一直停留在一个界面&#xff1a;“配置Windows Update失败&#xff0c;还原更改请勿关闭计算机”&#xff0c;等了许久还是无法进入系统。如果我们遇到此类问题应该如何解决呢&#xff0…...

    2022/11/19 21:16:58
  44. 如何在iPhone上关闭“请勿打扰”

    Apple’s “Do Not Disturb While Driving” is a potentially lifesaving iPhone feature, but it doesn’t always turn on automatically at the appropriate time. For example, you might be a passenger in a moving car, but your iPhone may think you’re the one dri…...

    2022/11/19 21:16:57