欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue 2.5.1 源码学习 之Vue.extend 和 data的合并策略

程序员文章站 2022-07-05 20:50:21
1. 子类父类  2.vue.extend()      //创建vue的子类   组件的语法器 vue.e...

1. 子类父类

 2.vue.extend()      //创建vue的子类

  组件的语法器 vue.extend(options)

  profile().$mount('#app') // 挂在app上,并替换app

  新建 initexend

  ==》 vue.extend

 3. strat.data

  ==> if(!vm){子组件中data的值是一个方法function ==> mergedataorfn()} // 数据的合并

  ==> else {} //通过实例绑定的data 实际是一个函数 mergedataorfn

  ==》 mergedataorfn if(!vm) mergedatafn ==> mergedata()

            else ==》mergedinstancedatafn ==>mergedata()

    mergedata(to,from) //终极合并

  jquery.extend // 深copy和浅copy

// 大体思路 (二)
// 1. 子类父类 
/* 
   2.vue.extend()  //创建vue的子类
   组件的语法器 vue.extend(options)
   profile().$mount('#app') // 挂在app上,并替换app
   新建 initexend  
     ==》 vue.extend
*/
/* 3. strat.data  
  ==> if(!vm){子组件中data的值是一个方法function ==> mergedataorfn()} // 数据的合并
  ==> else {} //通过实例绑定的data 实际是一个函数 mergedataorfn 
  ==》 mergedataorfn if(!vm) mergedatafn ==> mergedata()  
     else ==》mergedinstancedatafn ==>mergedata()
  mergedata(to,from) //终极合并
  jquery.extend // 深copy和浅copy
*/
(function(global,factory){
  // 兼容 cmd 
  typeof exports === 'object' && module !== 'undefined' ? module.exports = factory():  
  // amd
  typeof define === 'function' && define.amd ? define(factory) : global.vue = factory();
})(this,function(){
  var uip = 0;
  function warn(string){
    console.error('vue wran:' + string)
  }
  function resolveconstructoroptions(con){
    var options = con.options;
    // 判断是否为vm的实例 或者是子类
     return options
  }
  var hasownpropeerty = object.prototype.hasownproperty
  function hasown(obj , key){
    return hasownpropeerty.call(obj,key)
  }
  function makemap(str, expectslowerasec){
    if(expectslowerasec){
      str = str.tolowercase()
    }
    var map = object.create(null)
    var list = str.split(',')
    for(var i = 0 ; i < list.length; i++){
      map[list[i]] = true
    }
    return function(key){
      return map[key]
    }
  }
  var isbuiltintag = makemap('slot,component',true)
  var ishtmltag = makemap(
    'html,body,base,head,link,meta,style,title,' +
    'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
    'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
    'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
    's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
    'embed,object,param,source,canvas,script,noscript,del,ins,' +
    'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
    'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
    'output,progress,select,textarea,' +
    'details,dialog,menu,menuitem,summary,' +
    'content,element,shadow,template,blockquote,iframe,tfoot'
  );
  var issvg = makemap(
    'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
    'foreignobject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
    'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
    true
  );
  var isreservedtag = function(key){
    return ishtmltag(key) || issvg(key) 
  }
  function validatacomponentname(key){
    //检测component 的自定义名称是否合格 
    // 只能是字母开头或下划线,必须是字母开头
    if(!(/^[a-za-z][\w-]*$/g.test(key))){
      warn('组件的名称必须是字母或中横线,必须由字母开头')
    }
    // 1. 不能为内置对象,2.不能是html ,和avg的内部标签
    if( isbuiltintag(key) || isreservedtag(key)){
      warn('不能为html标签或者avg的内部标签')
    } 
  }
  function checkcomonpents(child){
    for(var key in child.component){
      validatacomponentname(key)
    }
  }
  // 配置对象
  var config = {
    // 自定义的策略
    optionmergestrategies:{}
  }
  var strats = config.optionmergestrategies
  strats.el = function(parent,child , key , vm){
     if(!vm){
       warn('选项'+key+'只能在vue实例用使用')
     }
     return defaultstrat(parent,child , key , vm)
  }
  function mergedata(to,form){
    // 终极合并
    if(!form){
      return to
    }
  }
  function mergedataorfn(parentval,childval,vm){
    // 合并 parentval childval 都是函数
    if(!vm){
      if(!childval){
        return parentval
      }
      if(!parentval){
        return childval
      }
      return function mergedatafn(parentval,childval,vm){//只是一个函数  什么样的情况下调用 加入响应式系统 
        // 合并子组件对应的data 和  父组件对应的data
        return mergedata( 
          typeof parentval === 'function' ? parentval.call(this,this) : parentval,  // -----忘记写
          typeof childval === 'function' ? childval.call(this,this): childval)   // -----忘记写
      }
    }else{ // vue实例
      return function mergeinstancedatafn(parentval,childval,vm){//只是一个函数  什么样的情况下调用 加入响应式系统 
        var instancedata = typeof childval === 'function' ? childval.call(vm,vm): childval;  // -----忘记写
        var defaultdata = typeof parentval === 'function' ? parent.call(vm,vm): parentval;  // -----忘记写
        if(instancedata){
          return mergedata(parentval,childval)
        }else{        // -----忘记写
          defaultdata
        }
      }
    }
  }
  strats.data = function(parent,child , key , vm){
    if(!vm){
     // console.log(typeof child === 'function')
      if(child && !(typeof child === 'function')){
        warn('data必须返回是一个function')
      }
      return mergedataorfn(parent,child)
    }
    return mergedataorfn(parent,child,vm)
  }
  function defaultstrat(parent,child , key , vm){
    return child === undefined ? parent :child ;
  }
  function mergeoptions(parent,child,vm){
    var options = {}
    // 检测是component 是否是合法的 
    checkcomonpents(child)
    // console.log(parent, child)
    for(key in parent){
      magerfield(key)
    }
    for(key in child){
      if(!hasown(parent ,key)){ // parent 中循环过地方不进行循环
        magerfield(key) // ----忘记写
      }
    }
    // 默认合并策略
    function magerfield(key){ 
      // 自定义策略 默认策略 
      // console.log(key)
      var result = strats[key] || defaultstrat    // ---忘记写
      options[key] = result(parent[key],child[key] , key , vm)
    }
    // console.log(options)
    return options
  }
  function initminxin(options){
    vue.prototype._init = function(options){
      var vm = this 
      // 记录生成的vue实例对象 
      vm._uip = uip++ //  //-------忘记写
       vm.$options =mergeoptions(resolveconstructoroptions(vm.constructor),options,vm)
    }
  }
  function vue(options){
    // 安全机制
    if(!(this instanceof vue)){   //-------忘记写
      warn('vue是一个构造函数,必须是由new关键字调用') 
    }
    this._init(options)
  }
  initminxin() // 初始化选项1: 规范 2: 合并策略。
  vue.options = {
    components: {},
    directives:{},
    _bash: vue
  }
  function initexend(vue){
    vue.extend = function(extendoptions){
      extendoptions = extendoptions || {}  // -----忘记写
      var super = this 
      var child = function vuecomponent() {
        this._init(options)
      }
      child.prototype = object.create(super.prototype)
      child.prototype.constructor = child  // 改变constructor 的指向
      child.options = mergeoptions(super.options,extendoptions)
      // 子类继承父类的静态方法。
      child.extend = vue.extend
      return child
    }
  }
  initexend(vue)
  return vue
})
<body>
  <div id="app">
    <huml></huml>
  </div>
  <script src="vue.js"></script>
  <!-- <script src="vue2.5.1.js"></script> -->
  <script type="text/javascript">
    var componenta = {
      el: "#app"
    }
    var vm = new vue({
      el:"#app",
      data: {
        message: "hello vue",
        key: "wodow"
      },
      components:{
        huml: componenta
      }
    })
    // console.log(vue)
    var parent = vue.extend({
      data: function() {}
    })
    var child = parent.extend({});
    console.log(vm.$options)
  </script>
</body>

总结

以上所述是小编给大家介绍的vue 2.5.1 源码学习 之vue.extend 和 data的合并策略,希望对大家有所帮助