Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue 源码阅读【1】—— Vue本质 #56

Open
amandakelake opened this issue Sep 26, 2018 · 2 comments
Open

Vue 源码阅读【1】—— Vue本质 #56

amandakelake opened this issue Sep 26, 2018 · 2 comments
Labels

Comments

@amandakelake
Copy link
Owner

写了一个月的vue项目,个人感觉,emm…
一旦熟悉了尤大给我们画好的舒适圈,很容易就陷在业务代理里,主要是vue封装的太好了,写代码几乎不用脑,只要按照规范一顿瞎写,怎么都过得去。
长久下去,写多了感觉会废,暂时还没用到服务端渲染,就是简单的前后端分离的web app,要想深入一点,感觉还是得多看看源码,免得最后成为了API工程师

前端娱乐圈,之前有一条喷vue,说用vue的都是小白或者菜鸟,其实从某种角度来说也有点道理

个人一直认为,三大框架框架没有优劣之分,只有最合适的业务场景,都是神写出来的东西,我等凡人达不到那个水平之前,何来的资格讨论人家的优劣;个人喜好与客观优劣不是一回事。

但对于用框架的人本身来说,那还是有点影响的,react越用越灵活,vue越用越。。。看完源码再说哈哈哈

这个vue源码阅读系列,参考着各路大神的文章学习,都是记录来自己看的,不太合适star了本blog的朋友们观看

Vue定义

src/core/instance/index.js

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')
  }
  this._init(options)
}

initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)

export default Vue

Vue实质上是一个Function实现的类,只能通过new Vue去实例化它

为何不用ES6的class去实现呢?
因为下面有很多xxxMixin的函数调用,用于给Vue的prototype上扩展一些方法,而这些扩展需要按照功能分散到各个模块中去实现,而不是在一个模块里实现所有,这些方式是class难以实现的。
这样做的好处是非常方便代码的维护和管理

src/core/global-api/index.js中还通过initGlobalAPI方法给Vue对象扩展了一些全局的静态方法

export function initGlobalAPI (Vue: GlobalAPI) {
  // config
  const configDef = {}
  configDef.get = () => config
  if (process.env.NODE_ENV !== 'production') {
    configDef.set = () => {
      warn(
        'Do not replace the Vue.config object, set individual fields instead.'
      )
    }
  }
  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 = set
  Vue.delete = del
  Vue.nextTick = nextTick

  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 = Vue

  extend(Vue.options.components, builtInComponents)

  initUse(Vue)
  initMixin(Vue)
  initExtend(Vue)
  initAssetRegisters(Vue)
}
@Daisy1213
Copy link

你好,请问上面提到说” Vue需要在原型上增加一些函数,这些方式是class难以实现的“ 这句我没理解,具体是怎么难以实现呢,我自己尝试了没找到问题,还请解答一些呢~

@ciloi
Copy link

ciloi commented Apr 27, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants