草庐IT

Vue——initState【十】

。思索 2023-03-28 原文

前言

前面我们简单的了解了 vue 初始化时的一些大概的流程,这里我们详细的了解下具体的内容;

内容

这一块主要围绕init.ts中的initState进行剖析,初始化生命周期之后紧接着。

initState

initState的方法位于scr/core/instance/state.ts中;

const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

export function proxy(target: Object, sourceKey: string, key: string) {
  // get方法
  sharedPropertyDefinition.get = function proxyGetter() {
    return this[sourceKey][key]
  }
  // set方法
  sharedPropertyDefinition.set = function proxySetter(val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

export function initState(vm: Component) {
  const opts = vm.$options
  // 存在props则初始化props
  if (opts.props) initProps(vm, opts.props)

  // Composition API
  // 初始化组合式API
  initSetup(vm)
  // 存在方法则初始化方法
  if (opts.methods) initMethods(vm, opts.methods)
  // 存在data则初始化data
  if (opts.data) {
    initData(vm)
  } else {
    const ob = observe((vm._data = {}))
    ob && ob.vmCount++
  }
  // 存在计算属性则初始化计算属性
  if (opts.computed) initComputed(vm, opts.computed)
  // 存在监听且监听不等于nativeWatch(这个主要是针对火狐浏览器进行处理)则初始化监听
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

function initProps(vm: Component, propsOptions: Object) {
  const propsData = vm.$options.propsData || {}
  const props = (vm._props = shallowReactive({}))
  // cache prop keys so that future props updates can iterate using Array
  // instead of dynamic object key enumeration.
  // 缓存prop的keys以便将来更新props时可以使用数组代替动态的迭代对象key
  const keys: string[] = (vm.$options._propKeys = [])
  // 判断是否是根组件
  const isRoot = !vm.$parent
  // root instance props should be converted
  if (!isRoot) {
    // 如果不是根组件就关闭响应式处理,防止defineReactive做响应式处理
    toggleObserving(false)
  }
  for (const key in propsOptions) {
    keys.push(key)
    // 对prop数据进行校验
    const value = validateProp(key, propsOptions, propsData, vm)
    /* istanbul ignore else */
    if (__DEV__) {
      const hyphenatedKey = hyphenate(key)
      // 检查属性是否是保留属性
      if (
        isReservedAttribute(hyphenatedKey) ||
        config.isReservedAttr(hyphenatedKey)
      ) {
        warn(
          `"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
          vm
        )
      }
      defineReactive(props, key, value, () => {
        if (!isRoot && !isUpdatingChildComponent) {
          warn(
            `Avoid mutating a prop directly since the value will be ` +
              `overwritten whenever the parent component re-renders. ` +
              `Instead, use a data or computed property based on the prop's ` +
              `value. Prop being mutated: "${key}"`,
            vm
          )
        }
      })
    } else {
      defineReactive(props, key, value)
    }
    // static props are already proxied on the component's prototype
    // during Vue.extend(). We only need to proxy props defined at
    // instantiation here.
    // 在Vue.extend()过程中,静态props已经在组件的原型上被代理。我们只需要在这里实例化时代理定义的props。
    if (!(key in vm)) {
      proxy(vm, `_props`, key)
    }
  }
  // 开启响应式处理
  toggleObserving(true)
}

/**
 * 初始化data
 * @param vm
 */
function initData(vm: Component) {
  let data: any = vm.$options.data
  // 通过getData将函数转为对象
  data = vm._data = isFunction(data) ? getData(data, vm) : data || {}
  if (!isPlainObject(data)) {
    data = {}
    // https://v2.cn.vuejs.org/v2/guide/components.html#data-%E5%BF%85%E9%A1%BB%E6%98%AF%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0
    // 一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝
    // 避免了实例之间相互影响
    __DEV__ &&
      warn(
        'data functions should return an object:\n' +
          'https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
        vm
      )
  }
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    // 检查key名是否在methods中已经使用
    if (__DEV__) {
      if (methods && hasOwn(methods, key)) {
        warn(`Method "${key}" has already been defined as a data property.`, vm)
      }
    }
    // 检查key名是否在props中使用
    if (props && hasOwn(props, key)) {
      __DEV__ &&
        warn(
          `The data property "${key}" is already declared as a prop. ` +
            `Use prop default value instead.`,
          vm
        )
      // 检查key名是否符合规范,即不以$和_开头
    } else if (!isReserved(key)) {
      // 代理数据 |本质上还是 Object.defineProperty
      proxy(vm, `_data`, key)
    }
  }
  // observe data | 响应式数据
  const ob = observe(data)
  ob && ob.vmCount++
}
/**
 * 获取data内容|转为对象
 * @param data
 * @param vm
 * @returns
 */
export function getData(data: Function, vm: Component): any {
  // #7573 disable dep collection when invoking data getters
  pushTarget()
  try {
    return data.call(vm, vm)
  } catch (e: any) {
    handleError(e, vm, `data()`)
    return {}
  } finally {
    popTarget()
  }
}

const computedWatcherOptions = { lazy: true }

function initComputed(vm: Component, computed: Object) {
  // $flow-disable-line
  // 创建一个空对象
  const watchers = (vm._computedWatchers = Object.create(null))
  // computed properties are just getters during SSR
  // 计算的内容只是SSR期间的getter
  // 是否服务端渲染
  const isSSR = isServerRendering()

  for (const key in computed) {
    const userDef = computed[key]
    const getter = isFunction(userDef) ? userDef : userDef.get
    if (__DEV__ && getter == null) {
      warn(`Getter is missing for computed property "${key}".`, vm)
    }

    if (!isSSR) {
      // create internal watcher for the computed property.
      // 不是服务端渲染,就为计算属性创建内部观察程序。
      // noop 空函数:function() {}
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }

    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    // 组件定义的计算内容已经在组件原型上定义。我们只需要在这里定义实例化时定义的计算内容。
    if (!(key in vm)) {
      defineComputed(vm, key, userDef)
    } else if (__DEV__) {
      // 开发环境下检查key名是否被过早的定义在data,props,methods中
      if (key in vm.$data) {
        warn(`The computed property "${key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      } else if (vm.$options.methods && key in vm.$options.methods) {
        warn(
          `The computed property "${key}" is already defined as a method.`,
          vm
        )
      }
    }
  }
}

export function defineComputed(
  target: any,
  key: string,
  userDef: Record<string, any> | (() => any)
) {
  // 是否服务端渲染
  const shouldCache = !isServerRendering()
  // 定义get和set
  if (isFunction(userDef)) {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  if (__DEV__ && sharedPropertyDefinition.set === noop) {
    sharedPropertyDefinition.set = function () {
      warn(
        `Computed property "${key}" was assigned to but it has no setter.`,
        this
      )
    }
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

function createComputedGetter(key) {
  return function computedGetter() {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      // 是否被计算过,如果dirty为true表明未被计算过
      if (watcher.dirty) {
        watcher.evaluate() // 调用watcher.get方法,值会保存在watcher.value上
      }
      if (Dep.target) {
        if (__DEV__ && Dep.target.onTrack) {
          Dep.target.onTrack({
            effect: Dep.target,
            target: this,
            type: TrackOpTypes.GET,
            key
          })
        }
        watcher.depend()
      }
      return watcher.value
    }
  }
}

function createGetterInvoker(fn) {
  return function computedGetter() {
    return fn.call(this, this)
  }
}

function initMethods(vm: Component, methods: Object) {
  const props = vm.$options.props
  // 循环遍历methods
  for (const key in methods) {
    if (__DEV__) {
      // 不是函数类型发出警告
      if (typeof methods[key] !== 'function') {
        warn(
          `Method "${key}" has type "${typeof methods[
            key
          ]}" in the component definition. ` +
            `Did you reference the function correctly?`,
          vm
        )
      }
      // 函数名称和props中的是否冲突
      if (props && hasOwn(props, key)) {
        warn(`Method "${key}" has already been defined as a prop.`, vm)
      }
      // 函数名不能以_和$开头
      if (key in vm && isReserved(key)) {
        warn(
          `Method "${key}" conflicts with an existing Vue instance method. ` +
            `Avoid defining component methods that start with _ or $.`
        )
      }
    }
    // 将methods绑定在当前实例上
    vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
  }
}

function initWatch(vm: Component, watch: Object) {
  // 遍历watch
  for (const key in watch) {
    const handler = watch[key]
    // 是否是数组
    if (isArray(handler)) {
      // 循环创建watcher监听回调函数
      for (let i = 0; i < handler.length; i++) {
        createWatcher(vm, key, handler[i])
      }
    } else {
      // 创建watcher监听回调函数
      createWatcher(vm, key, handler)
    }
  }
}

function createWatcher(
  vm: Component,
  expOrFn: string | (() => any),
  handler: any,
  options?: Object
) {
  // 检查是否是普通对象
  if (isPlainObject(handler)) {
    // 将handler挂载到options属性上
    options = handler
    // 提取handler属性赋值给handler
    handler = handler.handler
  }
  // 是否是字符串
  if (typeof handler === 'string') {
    // 从实例中找到handler赋值给handler
    handler = vm[handler]
  }
  // 实例上的$watch方法
  return vm.$watch(expOrFn, handler, options)
}

有关Vue——initState【十】的更多相关文章

  1. 计算机毕业设计ssm+vue基本微信小程序的小学生兴趣延时班预约小程序 - 2

    项目介绍随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱小学生兴趣延时班预约小程序的设计与开发被用户普遍使用,为方便用户能够可以随时进行小学生兴趣延时班预约小程序的设计与开发的数据信息管理,特开发了小程序的设计与开发的管理系统。小学生兴趣延时班预约小程序的设计与开发的开发利用现有的成熟技术参考,以源代码为模板,分析功能调整与小学生兴趣延时班预约小程序的设计与开发的实际需求相结合,讨论了小学生兴趣延时班预约小程序的设计与开发的使用。开发环境开发说明:前端使用微信微信小程序开发工具:后端使用ssm:VU

  2. (附源码)vue3.0+.NET6实现聊天室(实时聊天SignalR) - 2

    参考文章搭建文章gitte源码在线体验可以注册两个号来测试演示图:一.整体介绍  介绍SignalR一种通讯模型Hub(中心模型,或者叫集线器模型),调用这个模型写好的方法,去发送消息。  内容有:    ①:Hub模型的方法介绍    ②:服务器端代码介绍    ③:前端vue3安装并调用后端方法    ④:聊天室样例整体流程:1、进入网站->调用连接SignalR的方法2、与好友发送消息->调用SignalR的自定义方法 前端通过,signalR内置方法.invoke()  去请求接口3、监听接受方法(渲染消息)通过new signalR.HubConnectionBuilder().on

  3. vue 实现内容超出两行显示展开更多功能,可依据需求自定义任意行数! - 2

    平时开发中我们经常会遇到这样的需求,在一个不限高度的盒子中会有很多内容,如果全部显示用户体验会非常不好,所以可以先折叠起来,当内容达到一定高度时,显示展开更多按钮,点击即可显示全部内容,先来看看效果图: 这样做用户体验瞬间得到提升,接下来看看具体细节。0">主要操作在内容这里{{item.username}},……展开更多样式大家可依据自己项目需求进行设计,这里就不贴了,主要说几个关键的。1、在data中定义三个属性isShowMore:false, //控制展开更多的显示与隐藏textHeight:null, //框中内容的高度status:false, //内容状态是否打开2.计算内容是否

  4. vue3.0 + vite2.0+如何兼容低版本浏览器 - 2

    这里写自定义目录标题一、问题二、解决三、解决方案四、打包预览一、问题在使用vue3.2和vite2开发一个移动端或者钉钉端H5微服务iosapp内置浏览器打开没问题安卓app内置浏览器打开空白页面vconsole打印出现报错globalthisundefind二、解决内置浏览器版本比较低打印出来是63vue3代码不兼容低版本浏览器三、解决方案步骤一:vite.config.ts里build.target配置项指定构建目标为es2015或者步骤二:安装@vitejs/plugin-legacy安装完报错也还在指定版本可以解决“@vitejs/plugin-legacy”:“1.8.0”,步骤三:

  5. Vue3的新特性 - 2

    Vue3的新特性包括:CompositionAPI:一种新的API风格,可将有关组件功能的代码逻辑封装在单独的函数中,从而更好地管理和重用代码。Teleport:可以让组件在DOM层次结构中的任何位置渲染。Suspense:一种新的异步渲染模式,可以优化应用程序的性能。更快的渲染速度:Vue3使用了新的虚拟DOM算法,并且对渲染过程进行了优化,因此在渲染大型应用时性能更高。更小的包大小:Vue3的打包大小比Vue2更小,因为它不再需要依赖像vue-template-compiler这样的工具。其他改进:Vue3还具有其他一些改进,例如更好的TypeScript支持、更好的错误提示和更好的调试工

  6. vue2+element-ui,el-aside侧边栏容器收缩与展开 - 2

    一、概览实现效果如下:二、项目环境1、nodejs版本node-vv16.16.02、npm版本npm-vnpmWARNconfigglobal`--global`,`--local`aredeprecated.Use`--location=global`instead.8.15.03、vue脚手架版本vue-V@vue/cli5.0.8三、创建vue项目1、创建名为vuetest的项目vuecreatevuetest选择Default([Vue2]babel,eslint)  2、切换到项目目录,启动项目cdvuetestnpmrunserve 3、使用浏览器预览 http://localh

  7. Vue学习笔记:Vue element-ui中table组件的使用----接入后端数据 - 2

    记个笔记以免遗忘,建议还是查看Element-UI提供的官方文档学习,自己摸索比较难受官方文档:Element-UI组件TableElement-UI官网提供了许多Table格式,这里以一个带有筛选器的表格为例表格的官网显示效果:直接将官方提供的示例代码贴入.vue文件中即可使用显示的数据是通过data()方法提供的假数据。方法见下:data(){return{tableData:[{date:'2016-05-02',name:'王小虎',address:'上海市普陀区金沙江路1518弄'},{date:'2016-05-04',name:'王小虎',address:'上海市普陀区金沙江路1

  8. ruoyi-vue 新建模块--若依前后端分离系统代码生成。 - 2

    目录:1.在数据库中创建表2.使用代码生成功能,生成基础代码2.1修改代码生成器中配置文件generator.yml2.2使用系统工具代码生成3.新建子模块,迁移代码3.1创建grayskyax-assetsmanagement模块3.2在RuoYi整个项目下的`pom.xml`中引入刚刚新建的模块:3.3在ruoyi-admin模块的pom.xml中引入新建的模块3.4在新建的assetsManagement模块中引入ruoyi-common模块3.5将之前解压后的文件放如项目的对应目录下;3.6在数据库中执行生成的sql脚本3.7配置扫描路径application.yml,applicat

  9. 项目部署——Vue项目部署到云服务器(linux) - 2

    因为期末了,要检查web大作业,虽然没有要求,但我想把项目部署一下,以免每次都要打开运行了,部署过踩了许多坑,这里总结一一下这次部署的流程吧。项目我个人进行前后端分离的全栈开发,有后台,后台部署的过程由于篇幅原因将在下一篇中讲解准备工作准备一台虚拟机或者云服务器(linux系统)首先,由于真实的项目基本上都部署在linux系统上,因此为了贴近真实,我们需要准备一台带有linux系统的虚拟机或者云服务器,由于虚拟机不能在自己的电脑关机了以后继续运行,因此这里推荐云服务器,目前用过阿里云,腾讯云两款云服务器部署项目,操作基本上都十分简单。新用户可以在腾讯云和阿里云平台都有两周的免费云服务器可以领取

  10. javascript - vue.js中v-show的回调 - 2

    有没有使用vue.js的on-shown和on-show的回调方法?我在div元素上使用v-show="my-condition"。但里面有一些charts.js图表,除非可见,否则无法呈现。任何人都知道如何仅在父级可见时才渲染chart.js?它们位于可选择的选项卡内,因此它可能会触发多次。我正在使用Vue.js和vue-strap。 最佳答案 查看thisanswer-在类似情况下,使用nextTick()对我有用。简而言之:newVue({...data:{myCondition:false},watch:{myConditi

随机推荐