当前位置: 首页 > Web前端 > vue.js

vue源码分析(入门分析)

时间:2023-04-01 10:47:17 vue.js

找到vue入口文件,查看dist/vue.js的构建过程运行npmrundev时,指定配置文件,从配置文件script/config.js启动web-full-dev(web包含开发版的编译器和运行时)脚本/config.js基于节点的模块“dev”:“rollup-w-cscripts/config.js-m--environmentTARGET:web-full-dev”配置文件config.js...//判断是否有环境变量targetif(process.env.TARGET){module.exports=genConfig(process.env.TARGET)}else{exports.getBuild=genConfigexports.getAllBuilds=()=>Object.keys(builds).map(genConfig)}genratorconfig生成配置文件functiongenConfig(name){constopts=builds[name]...returnconfig}我们传入的环境变量指向开发版本的编译器inbuildconstbuilds={'web-full-dev':{//resolve将下面的路径转为绝对路径//实际得到的是src/platforms/web/entry-runtime-with-compiler.js//resolve方法会找到上面的路径,还有一个别名来操作entry:resolve('web/entry-runtime-with-compiler.js'),dest:resolve('dist/vue.js'),format:'umd',env:'development',别名:{he:'./entity-decoder'},//打包文件头部banner:bannerfunctionbanner}}问题:如果template和render同时设置,会被执行WHO?constvm=newVue({el:"#app",template:"

HelloTemplate

",render(h){returnh('h4',"HelloRender")}})解析入口对应的入口文件,并回答上面的问题从入口文件,src/platforms/web/entry-runtime-with-compiler.jsel是一个dom元素el不能是body或者html标签如果没有render,转换templatetorender如果函数有render,直接调用mount挂载DOM断点调试$mount方法注意npmrunbuild时没有启用sourcemap,如果要调试源码需要加上//#sourceMappingURL=vue.js.map到vue.js,可以调试vue.js源码或者修改配置文件加上-m,所以当前入口文件的作用是重写原型$mount方法,处理template模板,然后导出vue实例(带编译器的版本)注意和entry-runtime.js不同,不处理tempalte代码,vue实例(runtimeversion)直接返回。问:Vue的构造函数在哪里?Vue实例的成员/Vue的静态成员从哪里来?从入口文件反转,找到导入的地方...//#src/platforms/web/entry-runtime-with-compiler.jsimportVuefrom'./runtime/index'//Vue导入的地方。..exportdefaultVue解析src/platforms/web/runtime/index.js这个脚本主要是web平台相关的。处理Vue构造函数的脚本给出了Vue注册平台相关说明,在Vue原型上挂载了$mount,__patch__,Vue实例导出了,还是没有看到Vue构造函数!//#platforms/web/runtime/index.jssimportVuefrom'core/index'...exportdefaultVueparsingsrc/core/index.jscontinued发现上面介绍的Vuecore下的代码是platform-independentinitGlobalAPI(Vue)给Vue的构造函数添加了静态方法但是还是看不到Vue的构造函数!importVuefrom'./instance/index'...initGalobalAPI(Vue)...exportdefaultvueparsingsrc/core/instance/index.js与平台无关。最后,这里有Vue而不是使用class和使用constructor,原因是因为在Vue原型中添加成员方法方便给Vue实例添加成员,initialize...functionVue(options){if(process.env.NODE_ENV!=='production'&&!(thisinstanceofVue)){warn('Vueisaconstructorandshouldbecalledwiththe`new`keyword')}//initMixin中有这个方法this._init(options)}...总结:导出Vue的四个模块src/platforms/web/entry-runtime-with-compiler.jsweb平台相关的入口重写了平台相关的$mount()方法,注册了Vue。compile()方法,传递一个HTML字符串返回render函数src/platforms/web/runtime/index.jsweb平台相关注册和平台相关全局说明:v-model、v-show注册和平台相关全局components:v-transition,v-transition-groupglobalmethod:_patch_:将虚拟DOM转换为真实DOM$mount:src/cor的挂载方法e/index.js与平台无关。Vue的静态方法就设置好了。initGlobalAPI(Vue)src/core/instance/index.js与平台无关。定义构造函数,调用this._init(options)方法将普通实例成员混入Vue