<<往期回顾>>
接下来一起学习下,runtime-core里面的方法,本期主要实现的内容是,通过createApp方法,到mount最后把咋们的dom给挂载成功!,所有的源码请查看
咋们需要使这个测试用例跑成功!,在图中可以发现,调用app传入了一个render函数,然后挂载,对比期望结果!
思考再三,先把这一节先说了,jest是怎么来测试dom的?
jest默认的环境是node,在jest.config.js中可以看到
npm有在node中实现了浏览器环境的api的库,jsdom、happy-dom 等,咋们这里就使用比较轻的happy-dom,但是happy-dom里面与jest结合是一个子包——@happy-dom/jest-environment,那就安装一下
pnpm add @happy-dom/jest-environment -w -D
复制代码
由于我项目示例使用的是monorepo,所以只需要在runtime-core中进行以下操作即可:
在jest.config.js中修改环境
testEnvironment: '@happy-dom/jest-environment',
复制代码
然后你就可以在当前子包中使用正确运行测试用例了。
针对第一个问题,在上一节vue3源码分析——rollup打包monorepo中我们可以知道,在全局可以执行packages中的每一个脚本,同理,我们做以下操作:
// 在全局的package.json中的test修改成这句话
"test": "pnpm -r --filter=./packages/** run test",
复制代码
那么就可以执行啦!
第二个问题,这个是vscode的插件问题,我们可以重jest插件的文档入手,可以发现jest执行的时候,可以自定义脚本,解决办法如下:
意思是说,jest自动执行的时候,直接执行我们项目的test脚本,由于第一个问题的解决,第二个问题也是ok的哦!
在正文之前,希望您先看过本系列文章的 vue3 组件初始化流程,这里详细介绍了组件的初始化流程,这里主要是实现挂载
describe('apiCreateApp', () => {
// 定义一个跟节点
let appElement: Element;
// 开始之前创建dom元素
beforeEach(() => {
appElement = document.createElement('div');
appElement.id = 'app';
document.body.appendChild(appElement);
});
// 执行完测试后,情况html内部的内容
afterEach(() => {
document.body.innerHTML = '';
});
test('测试createApp,是否正确挂载', () => {
// 调用app方法,传入render函数
const app = createApp({
render() {
return h('div', {}, '123');
}
});
const appDoc = document.querySelector('#app')
// 调用mount函数
app.mount(appDoc);
expect(document.body.innerHTML).toBe('<div id="app"><div>123</div></div>');
})
})
复制代码
function createApp(rootComponent) {
const app = {
_component: rootComponent,
mount(container) {
const vnode = createVNode(rootComponent);
render(vnode, container);
}
};
return app;
}
复制代码
function createVNode(type, props, children) {
// 一开始咋们就是这么简单,vnode里面有一个type,props,children这几个关键的函数
const vnode = {
type,
props: props || {},
children: children || []
};
return vnode;
}
复制代码
function render(vnode, container) {
patch(vnode, container);
}
function patch(vnode, container) {
// patch需要判断vnode的type,如果是对象,则是处理组件,如果是字符串div,p等,则是处理元素
if (isObj(vnode.type)) {
processComponent(null, vnode, container);
} else if (String(vnode.type).length > 0) {
processElement(null, vnode, container);
}
}
复制代码
// n1 是老节点,n2则是新节点,container是挂载的容器
function processComponent(n1, n2, container) {
// 如果n1不存在,直接是挂载组件
if (!n1) {
mountComponent(n2, container);
}
}
复制代码
function mountComponent(vnode, container) {
// 创建组件实例
const instance = createComponentInstance(vnode);
// 处理组件,初始化setup,slot,props, render等在实例的挂载
setupComponent(instance);
// 执行render函数
setupRenderEffect(instance, vnode, container);
}
复制代码
// 是不是组件实例很简单,就只有一个vnode,props,
function createComponentInstance(vnode) {
const instance = {
vnode,
props: {},
type: vnode.type
};
return instance;
}
复制代码
function setupComponent(instance) {
const { props } = instance;
// 初始化props
initProps(instance, props);
// 处理组件的render函数
setupStatefulComponent(instance);
}
function setupStatefulComponent(instance) {
const Component = instance.type;
const { setup } = Component;
// 是否存在setup
if (setup) {
const setupResult = setup();
// 处理setup的结果
handleSetupResult(instance, setupResult);
}
// 完成render在instance中
finishComponentSetup(instance);
}
function handleSetupResult(instance, setupResult) {
// 函数作为instance的render函数
if (isFunction(setupResult)) {
instance.render = setupResult;
} else if (isObj(setupResult)) {
instance.setupState = proxyRefs(setupResult);
}
finishComponentSetup(instance);
}
function finishComponentSetup(instance) {
const Component = instance.type;
// 如果没有的话,直接使用Component的render
if (!instance.render) {
instance.render = Component.render;
}
}
复制代码
function setupRenderEffect(instance, vnode, container) {
const subtree = instance.render();
patch(subtree, container);
}
复制代码
// 这个方法和processComponent一样
function processElement(n1, n2, container) {
// 需要判断是更新还是挂载
if (n1) ; else {
mountElement(n2, container);
}
}
复制代码
function mountElement(vnode, container) {
// 创建根节点
const el = document.createElement(vnode.type);
const { props } = vnode;
// 挂载属性
for (let key in props) {
el.setAttribute(key, props[key]);
}
const children = vnode.children;
// 如果children是数组,继续patch
if (Array.isArray(children)) {
children.forEach((child) => {
patch(child, el);
});
} else if (String(children).length > 0) {
el.innerHTML = children;
}
// 把元素挂载到根节点
container.appendChild(el);
}
复制代码
恭喜,到这儿就完成本期的内容,重头看一下,vue组件的挂载分为两种,处理组件和处理元素,最终回归到处理元素上面,最后实现节点的挂载,该内容是经过非常多删减,只是为了实现一个基本挂载,还有许多的边界都没有完善,后续继续加油
我们都听过知其然知其所以然这句话
那么不知道大家是否思考过new Vue()这个过程中究竟做了些什么?
过程中是如何完成数据的绑定,又是如何将数据渲染到视图的等等
首先找到vue的构造函数
源码位置:src\core\instance\index.js
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
options是用户传递过来的配置项,如data、methods等常用的方法
vue构建函数调用_init方法,但我们发现本文件中并没有此方法,但仔细可以看到文件下方定定义了很多初始化方法
initMixin(Vue); // 定义 _init
stateMixin(Vue); // 定义 $set $get $delete $watch 等
eventsMixin(Vue); // 定义事件 $on $once $off $emit
lifecycleMixin(Vue);// 定义 _update $forceUpdate $destroy
renderMixin(Vue); // 定义 _render 返回虚拟dom
首先可以看initMixin方法,发现该方法在Vue原型上定义了_init方法
源码位置:src\core\instance\init.js
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to avoid this being observed
vm._isVue = true
// merge options
// 合并属性,判断初始化的是否是组件,这里合并主要是 mixins 或 extends 的方法
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else { // 合并vue属性
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
// 初始化proxy拦截器
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
// 初始化组件生命周期标志位
initLifecycle(vm)
// 初始化组件事件侦听
initEvents(vm)
// 初始化渲染方法
initRender(vm)
callHook(vm, 'beforeCreate')
// 初始化依赖注入内容,在初始化data、props之前
initInjections(vm) // resolve injections before data/props
// 初始化props/data/method/watch/methods
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`vue ${vm._name} init`, startTag, endTag)
}
// 挂载元素
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
仔细阅读上面的代码,我们得到以下结论:
initState方法是完成props/data/method/watch/methods的初始化
源码位置:src\core\instance\state.js
export function initState (vm: Component) {
// 初始化组件的watcher列表
vm._watchers = []
const opts = vm.$options
// 初始化props
if (opts.props) initProps(vm, opts.props)
// 初始化methods方法
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
// 初始化data
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
我们和这里主要看初始化data的方法为initData,它与initState在同一文件上
function initData (vm: Component) {
let data = vm.$options.data
// 获取到组件上的data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
// 属性名不能与方法名重复
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
// 属性名不能与state名称重复
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) { // 验证key值的合法性
// 将_data中的数据挂载到组件vm上,这样就可以通过this.xxx访问到组件上的数据
proxy(vm, `_data`, key)
}
}
// observe data
// 响应式监听data是数据的变化
observe(data, true /* asRootData */)
}
仔细阅读上面的代码,我们可以得到以下结论:
关于数据响应式在这就不展开详细说明
上文提到挂载方法是调用vm.$mount方法
源码位置:
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
// 获取或查询元素
el = el && query(el)
/* istanbul ignore if */
// vue 不允许直接挂载到body或页面文档上
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
// 存在template模板,解析vue模板文件
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
// 通过选择器获取元素内容
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
/**
* 1.将temmplate解析ast tree
* 2.将ast tree转换成render语法字符串
* 3.生成render方法
*/
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
阅读上面代码,我们能得到以下结论:
对template的解析步骤大致分为以下几步:
生成render函数,挂载到vm上后,会再次调用mount方法
源码位置:src\platforms\web\runtime\index.js
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
// 渲染组件
return mountComponent(this, el, hydrating)
}
调用mountComponent渲染组件
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
// 如果没有获取解析的render函数,则会抛出警告
// render是解析模板文件生成的
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
// 没有获取到vue的模板文件
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
// 执行beforeMount钩子
callHook(vm, 'beforeMount')
let updateComponent
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = () => {
const name = vm._name
const id = vm._uid
const startTag = `vue-perf-start:${id}`
const endTag = `vue-perf-end:${id}`
mark(startTag)
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
// 定义更新函数
updateComponent = () => {
// 实际调⽤是在lifeCycleMixin中定义的_update和renderMixin中定义的_render
vm._update(vm._render(), hydrating)
}
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
// 监听当前组件状态,当有数据变化时,更新组件
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
// 数据更新引发的组件更新
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
阅读上面代码,我们得到以下结论:
updateComponent方法主要执行在vue初始化时声明的render,update方法
render的作用主要是生成vnode
源码位置:src\core\instance\render.js
// 定义vue 原型上的render方法
Vue.prototype._render = function (): VNode {
const vm: Component = this
// render函数来自于组件的option
const { render, _parentVnode } = vm.$options
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots,
vm.$scopedSlots
)
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode
// render self
let vnode
try {
// There's no need to maintain a stack because all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = vm
// 调用render方法,自己的独特的render方法, 传入createElement参数,生成vNode
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
handleError(e, vm, `render`)
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
} catch (e) {
handleError(e, vm, `renderError`)
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
} finally {
currentRenderingInstance = null
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0]
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
)
}
vnode = createEmptyVNode()
}
// set parent
vnode.parent = _parentVnode
return vnode
}
_update主要功能是调用patch,将vnode转换为真实DOM,并且更新到页面中
源码位置:src\core\instance\lifecycle.js
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode
// 设置当前激活的作用域
const restoreActiveInstance = setActiveInstance(vm)
vm._vnode = vnode
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
// 执行具体的挂载逻辑
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
restoreActiveInstance()
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}
关注本头条号,每天坚持更新原创干货技术文章。
如需学习视频,请在微信搜索公众号“智传网优”直接开始自助视频学习
1. 前言
ExFAT(Extended File Allocation Table扩展文件分配表)是一种针对SD卡和USB闪存驱动器(U盘)等闪存设备进行优化的Microsoft专有文件系统。
它旨在取代旧的32位FAT32文件系统,后者不能存储大于4 GB的文件。
最新版本的Windows和MacOS操作系统支持exFAT文件系统。
CentOS与大多数其他主要Linux发行版一样,默认情况下不提供对专有exFAT文件系统的支持。
如果您使用CentOS作为操作系统,在尝试挂载exFAT格式的USB驱动器时可能会遇到问题。
本教程介绍如何在CentOS 7上启用exFAT支持,以使CentOS7可以支持exFAT文件系统,可以正常挂载exFAT的U盘。
centos挂载exfat u盘
2. CentOS系统怎么挂载exfat格式的U盘
为了能够在CentOS上安装exFAT文件系统,您需要安装免费的FUSE exFAT模块和工具,为类Unix系统提供全功能的exFAT文件系统管理。
在CentOS 7核心存储库中不提供exFAT软件包。 您可以选择从源构建exFAT工具,或者使用Nux Dextop软件仓库中的yum进行安装。 我们将选择第二种方案。
Nux软件仓库依赖于EPEL软件仓库。 如果系统上未启用EPEL存储库,请键入以下命令启用它:
sudo yum install epel-release
接下来,导入yum仓库GPG密钥并通过安装rpm软件包启用Nux存储库:
sudo rpm -v --import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro sudo rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm
启用软件仓库后,使用以下命令安装exfat-fuse和exfat-utils软件包:
sudo yum install exfat-utils fuse-exfat
完成了!您现在可以安装exFAT格式的设备。
CentOS系统怎么挂载exfat格式的U盘
3. 结论
本文主要介绍了如何在CentOS 7计算机上启用对exFAT文件系统的支持。 有些人将exFAT称为FAT64。
插入时USB驱动器将自动安装,但如果自动安装失败,则必须手动挂载exFAT格式的U盘。
centos7怎么挂载exfat格式U盘
本文已同步至博客站,尊重原创,转载时请在正文中附带以下链接:
https://www.linuxrumen.com/rmxx/1224.html
点击了解更多,快速查看更多的技术文章列表。
*请认真填写需求信息,我们会在24小时内与您取得联系。