当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 【js】vue 2.5.1 源码学习 (三) Vue.extend 和 data的合并策略

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

2019年06月04日  | 移动技术网IT编程  | 我要评论
大体思路 (三) 1. 子类父类 2.Vue.extend() //创建vue的子类 组件的语法器 Vue.extend(options) Profile().$mount('#app') // 挂在app上,并替换app 新建 initExend ==》 Vue.extend 3. strat.d ...
大体思路 (三)
 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>

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网