首页 > 语言 > JavaScript > 正文

深入理解Vue transition源码分析

2024-05-06 15:13:41
字体:
来源:转载
供稿:网友

这两天学习了Vue transition感觉这个地方知识点挺多的,而且很重要,所以,今天添加一点小笔记。

本来打算自己造一个transition的轮子,所以决定先看看源码,理清思路。Vue的transition组件提供了一系列钩子函数,并且具有良好可扩展性。

了解构建过程

既然要看源码,就先让Vue在开发环境跑起来,首先从GitHub clone下来整个项目,在文件./github/CONTRIBUTING.md中看到了如下备注,需要强调一下的是,npm run dev构建的是runtime + compiler版本的Vue。

# watch and auto re-build dist/vue.js$ npm run dev

紧接着在package.json中找到dev对应的shell语句,就是下面这句

"scripts": {  "dev": "rollup -w -c build/config.js --environment TARGET:web-full-dev",  ...}

Vue2使用rollup打包,-c 后面跟的是打包的配置文件(build/config.js),执行的同时传入了一个TARGET参数,web-full-dev。打开配置文件继续往里找。

...const builds = { ... 'web-full-dev': {   entry: resolve('web/entry-runtime-with-compiler.js'),   dest: resolve('dist/vue.js'),   format: 'umd',   env: 'development',   alias: { he: './entity-decoder' },   banner }, ...}

从上面的构建配置中,找到构建入口为web/entry-runtime-with-compiler.js,它也就是umd版本vue的入口了。 我们发现在Vue的根目录下并没有web这个文件夹,实际上是因为Vue给path.resolve这个方法加了个alias, alias的配置在/build/alias.js中

module.exports = { vue: path.resolve(__dirname, '../src/platforms/web/entry-runtime-with-compiler'), compiler: path.resolve(__dirname, '../src/compiler'), core: path.resolve(__dirname, '../src/core'), shared: path.resolve(__dirname, '../src/shared'), web: path.resolve(__dirname, '../src/platforms/web'), weex: path.resolve(__dirname, '../src/platforms/weex'), server: path.resolve(__dirname, '../src/server'), entries: path.resolve(__dirname, '../src/entries'), sfc: path.resolve(__dirname, '../src/sfc')}

web对应的目录为'../src/platforms/web',也就是src/platforms/web,顺着这个文件继续往下找。查看src/platforms/web/entry-runtime-with-compiler.js的代码,这里主要是处理将Vue实例挂载到真实dom时的一些异常操作提示, ,比如不要把vue实例挂载在body或html标签上等。但是对于要找的transition,这些都不重要,重要的是

import Vue from './runtime/index'

Vue对象是从当前目录的runtime文件夹引入的。打开./runtime/index.js,先查看引入了哪些模块, 发现Vue是从src/core/index引入的,并看到platformDirectives和platformComponents,官方的指令和组件八九不离十就在这了。

import Vue from 'core/index'......import platformDirectives from './directives/index'import platformComponents from './components/index'...// install platform runtime directives & componentsextend(Vue.options.directives, platformDirectives)extend(Vue.options.components, platformComponents)// install platform patch functionVue.prototype.__patch__ = inBrowser ? patch : noop            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选