【js】vue 2.5.1 源码学习 (三) Vue.extend 和 data的合并策略

大体思路 (三)
 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 //  1. 子类父类  
  3 /* 
  4      2.Vue.extend()    //创建vue的子类
  5      组件的语法器  Vue.extend(options)
  6      Profile().$mount('#app')  //  挂在app上,并替换app
  7      新建  initExend   
  8           ==》 Vue.extend 
  9 
 10 */
 11 /*  3. strat.data    
 12     ==> if(!vm){子组件中data的值是一个方法function ==> mergeDataorFn()} // 数据的合并
 13     ==> else {}  //通过实例绑定的data  实际是一个函数 mergeDataorFn 
 14     ==》 mergeDataorFn if(!vm) mergeDataFn  ==> mergeData()   
 15          else  ==》mergedInstanceDataFn ==>mergeData()
 16     mergeData(to,from)  //终极合并
 17     jquery.extend  // 深copy和浅copy
 18 */
 19 
 20   
 21 
 22 (function(global,factory){
 23     // 兼容 cmd  
 24     typeof exports === 'object'  && module !== 'undefined' ? module.exports = factory():   
 25     // Amd
 26     typeof define  === 'function' && define.amd ?  define(factory) : global.Vue = factory();
 27 })(this,function(){
 28     var uip = 0;
 29     function warn(string){
 30         console.error('Vue Wran:' + string)
 31     }
 32 
 33     function resolveConstructorOptions(Con){
 34         var options = Con.options;
 35         // 判断是否为vm的实例 或者是子类
 36           return options
 37     }
 38     var hasOwnPropeerty = Object.prototype.hasOwnProperty
 39     function hasOwn(obj , key){
 40         return hasOwnPropeerty.call(obj,key)
 41     }
 42     function makeMap(str, expectsLoweraseC){
 43         if(expectsLoweraseC){
 44             str = str.toLowerCase()
 45         }
 46         var map = Object.create(null)
 47         var list = str.split(',')
 48         for(var i = 0 ; i < list.length; i++){
 49             map[list[i]] = true
 50         }
 51         return function(key){
 52             return map[key]
 53         
 54         }
 55     }
 56     var  isbuiltInTag = makeMap('slot,component',true)
 57     var isHTMLTag = makeMap(
 58         'html,body,base,head,link,meta,style,title,' +
 59         'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
 60         'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
 61         'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
 62         's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
 63         'embed,object,param,source,canvas,script,noscript,del,ins,' +
 64         'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
 65         'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
 66         'output,progress,select,textarea,' +
 67         'details,dialog,menu,menuitem,summary,' +
 68         'content,element,shadow,template,blockquote,iframe,tfoot'
 69     );
 70     var isSVG = makeMap(
 71         'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
 72         'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
 73         'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
 74         true
 75     );
 76     var isReservedTag = function(key){
 77         return isHTMLTag(key) || isSVG(key) 
 78     }
 79     function validataComponentName(key){
 80         //检测component 的自定义名称是否合格 
 81         // 只能是字母开头或下划线,必须是字母开头
 82         if(!(/^[a-zA-Z][\w-]*$/g.test(key))){
 83            warn('组件的名称必须是字母或中横线,必须由字母开头')
 84         }
 85         // 1. 不能为内置对象,2.不能是html ,和avg的内部标签
 86         if( isbuiltInTag(key) || isReservedTag(key)){
 87             warn('不能为html标签或者avg的内部标签')
 88         } 
 89     }
 90     function checkComonpents(child){
 91         for(var key in child.component){
 92             validataComponentName(key)
 93         }
 94     }
 95    // 配置对象
 96     var config = {
 97         // 自定义的策略
 98         optionMergeStrategies:{}
 99     }
100     var strats = config.optionMergeStrategies
101     strats.el = function(parent,child , key , vm){
102        
103           if(!vm){
104               warn('选项'+key+'只能在vue实例用使用')
105           }
106           return defaultStrat(parent,child , key , vm)
107     }
108     function mergeData(to,form){
109         // 终极合并
110         if(!form){
111             return to
112         }
113     }
114     function mergeDataorFn(parentVal,childVal,vm){
115         // 合并 parentVal childVal  都是函数
116         if(!vm){
117             if(!childVal){
118                 return parentVal
119             }
120             if(!parentVal){
121                 return childVal
122             }
123            return  function mergeDataFn(parentVal,childVal,vm){//只是一个函数   什么样的情况下调用 加入响应式系统 
124                // 合并子组件对应的data 和   父组件对应的data
125                return mergeData( 
126                    typeof parentVal === 'function' ? parentVal.call(this,this) : parentVal,    // -----忘记写
127                    typeof childVal === 'function' ? childVal.call(this,this): childVal)      // -----忘记写
128            }
129         }else{ // vue实例
130             return function mergeInstanceDataFn(parentVal,childVal,vm){//只是一个函数   什么样的情况下调用 加入响应式系统 
131                 var InstanceData = typeof childVal === 'function' ? childVal.call(vm,vm): childVal;   // -----忘记写
132                 var defaultData = typeof parentVal === 'function' ? parent.call(vm,vm): parentVal;   // -----忘记写
133                 if(InstanceData){
134                     return mergeData(parentVal,childVal)
135                 }else{                // -----忘记写
136                     defaultData
137                 }
138                 
139             }
140         }
141     }
142     strats.data = function(parent,child , key , vm){
143         if(!vm){
144           // console.log(typeof child === 'function')
145             if(child && !(typeof child === 'function')){
146                 warn('data必须返回是一个function')
147             }
148            return mergeDataorFn(parent,child)
149         }
150         return mergeDataorFn(parent,child,vm)
151     }
152     function defaultStrat(parent,child , key , vm){
153         return child === undefined ? parent :child ;
154     }
155     function mergeOptions(parent,child,vm){
156         var options = {}
157         // 检测是component 是否是合法的  
158      
159         checkComonpents(child)
160         
161         // console.log(parent, child)
162         for(key in parent){
163             magerField(key)
164         }
165         for(key in child){
166             if(!hasOwn(parent ,key)){  // parent 中循环过地方不进行循环
167                 magerField(key)  // ----忘记写
168             }
169               
170         }
171         // 默认合并策略
172         function magerField(key){  
173             // 自定义策略  默认策略 
174             // console.log(key)
175             var result = strats[key] || defaultStrat        // ---忘记写
176             options[key] = result(parent[key],child[key] , key , vm)
177         }
178         // console.log(options)
179         return options
180     }
181     function initMinxin(options){
182         Vue.prototype._init = function(options){
183             var vm = this 
184             // 记录生成的vue实例对象 
185             vm._uip =  uip++ //   //-------忘记写
186           
187              vm.$options =mergeOptions(resolveConstructorOptions(vm.constructor),options,vm)
188         }
189     }
190     function Vue(options){
191         // 安全机制
192         if(!(this instanceof Vue)){     //-------忘记写
193             warn('Vue是一个构造函数,必须是由new关键字调用')  
194         }
195         this._init(options)
196     }
197     initMinxin()  //  初始化选项1: 规范 2: 合并策略。
198     Vue.options = {
199         components: {},
200         directives:{},
201         _bash: Vue
202     }
203     function initExend(Vue){
204         Vue.extend = function(extendOptions){
205             extendOptions = extendOptions || {}   // -----忘记写
206             var Super = this 
207             var Child = function VueComponent() {
208                 this._init(options)
209             }
210             Child.prototype = Object.create(Super.prototype)
211             Child.prototype.constructor = Child   // 改变constructor 的指向
212             Child.options = mergeOptions(Super.options,extendOptions)
213             // 子类继承父类的静态方法。
214             Child.extend = Vue.extend
215             return Child
216         }
217     }
218     initExend(Vue)
219     return Vue
220 })
 1 <body>
 2     <div id="app">
 3         <huml></huml>
 4     </div>
 5     <script src="vue.js"></script>
 6     <!-- <script src="vue2.5.1.js"></script> -->
 7     <script type="text/javascript">
 8         var componentA = {
 9             el: "#app"
10         }
11         var vm = new Vue({
12             el:"#app",
13             data: {
14                 message: "hello Vue",
15                 key: "wodow"
16             },
17             components:{
18                 huml: componentA
19             }
20             
21         })
22         // console.log(Vue)
23         var Parent = Vue.extend({
24             data: function() {}
25         })
26         var Child = Parent.extend({});
27         console.log(vm.$options)
28     </script>
29 </body>

以上仅个人在学习中的总结笔记,如有问题,请评论回复。

转载于:https://www.cnblogs.com/yeujuan/p/10968982.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值