vue源代码

    科技2026-08-20  9

    vue源代码

    重点 (Top highlight)

    从源代码学习 (Learn From Source Code)

    A very efficient way to learn a programming language is to read the source code of a good open-source project developed in that programming language. Vuejs is one of the best JavaScript open-source projects. While reading the Vue 2.x source code, I learned a lot about JavaScript usage, so I wrote this article.

    学习编程语言的一种非常有效的方法是读取以该编程语言开发的优秀开源项目的源代码。 Vuejs是最好JavaScript开源项目之一。 在阅读Vue 2.x源代码时,我学到了很多关于JavaScript的用法,因此我写了这篇文章。

    It should be noted that:

    应当指出的是:

    This article is mainly to summarize the use of vanilla JavaScript and does not cover the operation mechanism of Vue

    本文主要是对Vanilla JavaScript的使用进行总结,并不涉及Vue的操作机制。 You do not need a background on Vue to read this article.

    您不需要Vue的背景知识即可阅读本文。

    Many tips on the Vue source code are based on context. But I’ve simplified it a little bit to make it easier for the reader to understand. So the usage you’ll see in this article is slightly different from the actual Vue source code.

    Vue源代码上的许多技巧都是基于上下文的。 但是我对其进行了简化,以方便读者理解 。 因此,您将在本文中看到的用法与实际的Vue源代码略有不同。

    If you are interested in the Vue source code, you can find it in this link:

    如果您对Vue源代码感兴趣,可以在以下链接中找到它:

    浏览器环境嗅探 (Browser environment sniffing)

    vue/src/core/util/env.js

    vue / src / core / util / env.js

    We know that JavaScript can run in browsers, node, weex, etc., so how do we check if the current JavaScript code is running in a browser environment?

    我们知道JavaScript可以在浏览器,节点,weex等中运行,那么我们如何检查当前JavaScript代码是否在浏览器环境中运行?

    If JavaScript is running in a browser environment, then there must be a global object: window. So we can judge the environment in this way:

    如果JavaScript在浏览器环境中运行,则必须有一个全局对象: window 。 因此,我们可以通过以下方式判断环境:

    const inBrowser = typeof window !== 'undefined' Execute in Chrome 在Chrome中执行 Execute in node 在节点执行

    If the script is running in a browser environment, then we can get the browser’s userAgent in this way:

    如果脚本在浏览器环境中运行,那么我们可以通过以下方式获取浏览器的userAgent :

    const UA = inBrowser && window.navigator.userAgent.toLowerCase() Execute in Chrome 在Chrome中执行

    Different browsers have different userAgent. In the Internet Explorer’s userAgent, the words MSIE and Trident are always included. In the userAgent of the Chrome browser, the word Chrome is always included.

    不同的浏览器具有不同的userAgent。 在Internet Explorer的userAgent中,始终包含单词MSIE和Trident 。 在Chrome浏览器的userAgent中,始终包含Chrome一词。

    Similarly, in the Android operating system browser, the userAgent always contains the word Android. In iOS, there is always one of the words iPhone, iPad, iPod, iOS.

    同样,在Android操作系统浏览器中,userAgent始终包含单词 Androi d。 在iOS中,总有一个词 iPhone , iPad , iPod , iOS 。

    So we can determine the current browser vendor and operating system by examining the userAgent.

    因此,我们可以通过检查userAgent来确定当前的浏览器供应商和操作系统。

    const UA = inBrowser && window.navigator.userAgent.toLowerCase()const isIE = UA && /msie|trident/.test(UA)const isIE9 = UA && UA.indexOf('msie 9.0') > 0const isEdge = UA && UA.indexOf('edge/') > 0const isAndroid = (UA && UA.indexOf('android') > 0) const isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA))const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdgeconst isPhantomJS = UA && /phantomjs/.test(UA)const isFF = UA && UA.match(/firefox\/(\d+)/)

    As a side note, both Edge and Chrome are based on Chromium, so the userAgent for both browsers contains the word Chrome. That is, when the browser’s userAgent contains the word Chrome, the browser is not necessarily Chrome. So we need to write code like const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge in order to be sure that the current browser is Chrome.

    另外,Edge和Chrome都基于Chromium,因此两种浏览器的userAgent都包含Chrome 。 也就是说,当浏览器的userAgent包含单词Chrome ,浏览器不一定是Chrome。 因此,我们需要编写类似const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge代码,以确保当前的浏览器是Chrome。

    获取HTML格式的字符串中的非标记字符 (Gets non-tag characters in an HTML -formatted string)

    vue/src/compiler/parser/entity-decoder.js

    vue / src / compiler / parser / entity-decoder.js

    For example, we have some HTML strings that look like this:

    例如,我们有一些如下HTML字符串:

    var html1 = '<span class="red">hello world</span> <span>hello friend</span>'var html2 = `<ul> <li>Hello Medium!</li> <li>Hello Friends!</li> <li>Lorem, ipsum dolor.</li></ul>`

    We want to extract the non-tagged contents of these strings and get the following result:

    我们要提取这些字符串的未标记内容,并获得以下结果:

    'hello world hello friend'` Hello Medium! Hello Friends! Lorem, ipsum dolor.`

    If you had this problem, what would you do?

    如果您遇到此问题,该怎么办?

    The first thing we might think of is using regular expressions to parse strings. Of course, using regular expressions is theoretically possible, but the associated regular expressions can be cumbersome and error-prone.

    我们可能想到的第一件事是使用正则表达式解析字符串。 当然,使用正则表达式在理论上是可行的,但是关联的正则表达式可能很麻烦且容易出错。

    So is there a better way to think about it?

    那么,有没有更好的方法来考虑它呢?

    Here’s how smart Vue developers think about it:

    聪明的Vue开发人员是怎么想的:

    Since the string is in HTML format, we can parse the corresponding string into HTML elements

    由于字符串为HTML格式,因此我们可以将相应的字符串解析为HTML元素

    The textContent attribute of the HTML element is then used to obtain the text content within that element.

    然后,HTML元素的textContent属性用于获取该元素内的文本内容。

    Specifically, this is the code:

    具体来说,这是代码:

    function decoder(html){ let decoder = document.createElement('div') decoder.innerHTML = html console.log(decoder.textContent) // return decoder.textContent}

    This code first creates a DIV element as a container and then converts the string into an HTML element by setting the innerHTML. Finally, the text content of the element is obtained through the textContent attribute.

    此代码首先将DIV元素创建为容器,然后通过设置innerHTML将字符串转换为HTML元素。 最后,通过textContent属性获取元素的文本内容。

    And then let’s test it out.

    然后让我们对其进行测试。

    普通物体 (Plain Object)

    vue/src/shared/util.js

    vue / src / shared / util.js

    Object.prototype.toString allows you to convert an object into a string. For ordinary objects, when this method is called, it always returns [object Object] .

    Object.prototype.toString允许您将对象转换为字符串。 对于普通对象,调用此方法时,它总是返回[object Object] 。

    For this kind of object, we can call them plain objects.

    对于这种对象,我们可以称它们为普通对象。

    There are also special objects in JavaScript, such as Array, String, and RegExp, which have special designs in the JavaScript engine. So when they call this method, they return different results.

    JavaScript中还有一些特殊的对象,例如Array,String和RegExp,它们在JavaScript引擎中具有特殊的设计。 因此,当他们调用此方法时,它们将返回不同的结果。

    To distinguish these specially designed objects from those ordinary objects, we can write a function like this:

    为了将这些经过特殊设计的对象与那些普通对象区分开,我们可以编写如下函数:

    function isPlainObject (obj){ return Object.prototype.toString.call(obj) === '[object Object]'}

    字符串值 (Value to String)

    vue/src/shared/util.js

    vue / src / shared / util.js

    Turning a value into a string is a very common requirement. In JavaScript, we have two functions that convert values to strings:

    将值转换为字符串是非常普遍的要求。 在JavaScript中,我们有两个函数将值转换为字符串:

    String()

    串() JSON.stringify()

    JSON.stringify()

    These two functions have different mechanisms:

    这两个功能具有不同的机制:

    As you can see, there are completely different mechanisms for trying to convert a value into a string. So how do we choose?

    如您所见,尝试将值转换为字符串的机制完全不同。 那么我们该如何选择呢?

    when we want to convert null and undefined to a string, we often want it to return an empty string.

    当我们想将null和undefined转换为字符串时,我们经常希望它返回一个空字符串。

    when we turn an array and a plain object into a string, we often want to use JSON.stringify.

    当我们将一个数组和一个普通对象转换为字符串时,我们经常要使用JSON.stringify 。

    If the object’s toString method is overridden, then we want to use String().

    如果对象的toString方法被覆盖,则我们要使用String() 。

    In other cases, String() is used to convert the value to a String.

    在其他情况下,使用String()将值转换为字符串。

    To meet the above requirements, it is written in Vue as follows:

    为了满足上述要求,它使用Vue编写如下:

    function isPlainObject (obj){ return Object.prototype.toString.call(obj) === '[object Object]'}function toString (val) { if(val === null || val === undefined) return ''if (Array.isArray(val)) return JSON.stringify(val)if (isPlainObject(val) && val.toString === Object.prototype.toString) return JSON.stringify(val)// other cases return String(val)}

    一旦 (once)

    vue/src/shared/util.js

    vue / src / shared / util.js

    Many times, we want a function to be executed only once. If the function is called multiple times, only the first time will be executed.

    很多时候,我们希望一个函数只执行一次。 如果多次调用该函数,则只会执行第一次。

    So we can write a function that looks like this:

    因此,我们可以编写一个如下所示的函数:

    function once (fn) { let called = false return function () { if (!called) { called = true fn.apply(this, arguments) } }}

    Then let’s test this function.

    然后让我们测试一下此功能。

    function launchRocket(){ console.log('The rocket has been launched.')}const launchRocketOnce = once(launchRocket)launchRocketOnce()launchRocketOnce()launchRocketOnce()

    If you are interested in this article, you may consider reading my other article of the same type on Medium. It also introduces some JavaScript tips learned in the Vue source code. I hope they will be useful to you.

    如果您对本文感兴趣,则可以考虑在Medium上阅读我的同一类型的其他文章。 它还介绍了在Vue源代码中学到的一些JavaScript技巧。 希望它们对您有用。

    Thanks for reading!

    谢谢阅读!

    翻译自: https://medium.com/javascript-in-plain-english/learn-javascript-from-vue-source-code-d9d8516ea9c4

    vue源代码

    相关资源:vue2.5快速入门源代码
    Processed: 0.012, SQL: 9