Global configuration

Vue. Config is an object that contains the global configuration of Vue.

  • Source location: util/config.js
  • Search for config to find its source address, which declares the type and default parameters of config, leaving only the official configuration items below
export typeConfig = { // user optionMergeStrategies: { [key: string]: Function }; // Options for customizing merge policies. silent: boolean; // About logs and warnings productionTip: Boolean; / / set tofalseTo prevent vUE from generating production prompts on startup. performance: boolean; / / set totrueTo enable performance tracking for component initialization, compilation, rendering, and patching in the browser developer's performance/timeline panel. Only works in development mode and on browsers that support the Performance. Mark API. devtools: boolean; // Configure whether vue-devtools checks code. errorHandler: ? (err: Error, vm: Component, info: string) => void; // Specifies a handler that does not catch errors during rendering and viewing of the component. When this handler is called, it gets an error message and a Vue instance. warnHandler: ? (msg: string, vm: Component, trace: string) => void; // Assign a custom handler to Vue's runtime warnings. Note that this only works in the developer environment and is ignored in production. ignoredElements: Array<string | RegExp>; / / the Vue keyCodes to ignore outside Vue custom elements: {[key: string] : number | Array < number >}; // Customize the key alias for v-ON // platform..... Platform related...... };exportDefault ({default}: Config))Copy the code
  • Config is a separate example, and then the default configuration is exposed, so how can we use vue.confige.xxx?

  • Core /global-api/index.js
import config from '.. /config'.export function initGlobalAPI (Vue: GlobalAPI) {
  // config
  const configDef = {}
  configDef.get = () => config
  if(process.env.NODE_ENV ! = ='production') {
    configDef.set = () => {
      warn(
        'Do not replace the Vue.config object, set individual fields instead.'
      )
    }
  }
  Object.defineProperty(Vue, 'config', configDef)
....
}
Copy the code
  • We can see in this file that Vue injects config into the GLOBAL API. Again, the object.defineProperty () method is used to place it in the Vue instance. To sum up, I can feel that as a big framework, it is very refined for the dispersion and aggregation of various functions. The organizational structure is clear and clear. So let’s take a quick look at how the Config exposure apis provided by VUE generally work.

1, silent

  • Source address: core/util/debug.js
. warn = (msg, vm) => { const trace = vm ? generateComponentTrace(vm) :' '

    if (config.warnHandler) {
      config.warnHandler.call(null, msg, vm, trace)
    } else if(hasConsole && (! Config.silent)) {// Determine slinet console.error(' [Vue warn]:${msg}${trace}`)
    }
  }

  tip = (msg, vm) => {
    if(hasConsole && (! Config.silent)) {// Judge slient console.warn(' [Vue tip]:${msg}` + (
        vm ? generateComponentTrace(vm) : ' '))}}...Copy the code
  • Analysis: We can see that the use of slient by vue in debug.js is a very general judgment, needless to say.

2、 optionMergeStrategies

  • Core /util/option.js
. /** * Option overwriting strategies arefunctionsthat handle * how to merge a parent option value and a child option * value into the final value. */ const strats = config.optionMergeStrategies ... Do a lot of things to merge all kinds of data, data, methods, watch, etc...Copy the code
  • Analysis: OptionMergeStrategies are used primarily in mixin and Vue. Extend () methods where the child and parent components have the same option, we can see that optionMergeStrategies are used in Potion, Inside a variety of merge, because of which various types of merge strategy can be taken out in detail, this comb, nearly is to taste, regardless of in-depth, later have the opportunity to discuss, Vue more profound source analysis, or the first data-driven and responsive part of the main.

3、 devtools

  • Source address: core/observer/scheduler. Js & core/util/env. Js
/**
 * Flush both queues and run the watchers.
 */
function flushSchedulerQueue() {... // devtool hook /* istanbul ignoreif* /if (devtools && config.devtools) {
    devtools.emit('flush')}... }Copy the code
// detect devtools
export const devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__
Copy the code
  • VUE_DEVTOOLS_GLOBAL_HOOK {_buffer: Array(0), Vue: ƒ : ƒ… }. The emit method is used in scheduler.js. We only look at the support for Vue, not the implementation of this tool. FlushSchedulerQueue (), which is clear in the comments, is also a key method in the vUE response. To recap, vue iterates through the update process. We introduce the concept of a queue. This is also an optimization point when Vue does dispatches. Instead of triggering a watcher callback every time the data changes, it first adds the watcher to a queue and then executes the flushSchedulerQueue after nextTick. One after another
  1. Queue. Sort ((a, b) => a.id – b.id)
  2. Queue traversal After sorting the queue, the next step is to traverse it, get the corresponding watcher, and execute watcher.run().
  3. State restoration executes the resetSchedulerState function,

Generally speaking, the details are tedious. If you are interested, please refer to my follow-up section on nextTick on reactive processing.


4、 errorHandler

  • Source location core/util/error.js
function globalHandleError (err, vm, info) {
  if (config.errorHandler) {
    try {
      return config.errorHandler.call(null, err, vm, info) //
    } catch (e) {
      // if the user intentionally throws the original error in the handler,
      // do not log it twice
      if(e ! == err) {logError(e, null, 'config.errorHandler')}}}logError(err, vm, info)
}
Copy the code
  • This API is actually easy to understand from the official documentation.

Specifies a handler that does not catch errors during rendering and viewing of the component. When this handler is called, it gets an error message and a Vue instance.

Here feel no what to say ,,,, online to see a lot of analysis, I will not investigate the interest can click here


5, warnHandler

  • Source location core/util/error.js
 warn = (msg, vm) => {
    const trace = vm ? generateComponentTrace(vm) : ' '

    if (config.warnHandler) {
      config.warnHandler.call(null, msg, vm, trace)
    } else if(hasConsole && (! config.silent)) { console.error(`[Vue warn]:${msg}${trace}`)}}Copy the code
  • Analysis? Feel oneself level is limited, actual use is almost zero, do not have what analysis. Interested in this article, the author is doing research on Vue exception handling, here

6, ignoredElements

  • Source location core/dom/patch.js
  function isUnknownElement (vnode, inVPre) {
    return(!inVPre && ! vnode.ns && ! ( config.ignoredElements.length && config.ignoredElements.some(ignore => {returnisRegExp(ignore) ? Ignore. Test (vnode.tag) : ignore === vnode.tag})) && config.isunknownElement (vnode.tag))} //creatElm functionfunctioncreateElm ( ... / / {\ \... do more thingif(isDef(tag)) { ... //if (isUnknownElement(vnode, creatingElmInVPre)) {
          warn(
            'Unknown custom element: <' + tag + '> - did you ' +
            'register the component correctly? For recursive components, ' +
            'make sure to provide the "name" option.', vnode.context ) } } \\... do more thing }Copy the code
  • Analysis? The official documentation is very good,

Vue must be made to ignore custom elements outside of Vue (e.g., using the Web Components APIs). Otherwise, it will assume that you forgot to register the global component or misspelled the component name, and will throw a warning about the Unknown Custom Element.

The code is also clear. You can see that the error point occurs in Vue’s core data-driven method, creatElm. For more on data driven, see my related article.


7、 keyCodes

  • Core /instance/render-helpers/check-keycodes.js
function isKeyNotMatch<T> (expect: T | Array<T>, actual: T): boolean {
  if (Array.isArray(expect)) {
    return expect.indexOf(actual) === -1
  } else {
    returnexpect ! == actual } } /** * Runtime helperfor checking keyCodes from config.
 * exposed as Vue.prototype._k
 * passing in eventKeyName as last argument separately for backwards compat
 */
export functioncheckKeyCodes ( eventKeyCode: number, key: string, builtInKeyCode? : number | Array<number>, eventKeyName? : string, builtInKeyName? : string | Array<string> ): ? boolean { const mappedKeyCode = config.keyCodes[key] || builtInKeyCodeif(builtInKeyName && eventKeyName && ! config.keyCodes[key]) {return isKeyNotMatch(builtInKeyName, eventKeyName)
  } else if (mappedKeyCode) {
    return isKeyNotMatch(mappedKeyCode, eventKeyCode)
  } else if (eventKeyName) {
    returnhyphenate(eventKeyName) ! == key } }Copy the code
  • Analysis: This thing, I specifically practice, in fact, is a custom alias, I looked at the document at that time I was confused, I changed the following
Vue.config.keyCodes = {
  v: 86,
  "media-play-pause": 86,
}
<input type="text" @keyup.media-play-pause="method($event)">

Copy the code

In this case, you can see that the method is used to define its own alias for keyCode. In the case of the above code, the method is the same as V to get the value 86. Then go to the proxy, complete the proxy. Without further ado, it should be said that sometimes you can try it yourself to find out what the document says…


8 and prformance

Drink straight from the official instructions

Usage: Set to true to enable performance tracking for component initialization, compilation, rendering, and patching in the browser developer’s Performance/timeline panel. Only works in development mode and on browsers that support the Performance. Mark API.

To use it, you need to install a plugin. I’ve been having trouble installing it. I don’t know why. This part of the sequence performance optimization, temporarily I have not detailed to learn about understanding, here to leave a pit… Back fill.


9 productionTip.

  • Source address: platforms/web/runtime/index, js
.if(process.env.NODE_ENV ! = ='production'&& process.env.NODE_ENV ! = ='test'&& config.productionTip ! = =false&& typeof console ! = ='undefined'
    ) {
      console[console.info ? 'info' : 'log'](
        `You are running Vue in development mode.\n` +
        `Make sure to turn on production mode when deploying for production.\n` +
        `See more tips at https://vuejs.org/guide/deployment.html`
      )
...
Copy the code

If the official explanation, there is no need to repeat.

Usage: Set to false to prevent vue from generating production prompts on startup.


  • Summary of global configuration:
  1. Personally, the global configuration part is a superficial walk, to be honest, some of the content I almost never use, and indeed this comb, more like, CV documentation and source code. Without going into the details,
  2. The whole IDEA of Vue API sorting is to let me re-understand Vue, after all, Vue is a very big project, for each API can not be to study the details of the source code, but beg, have a concept, practical operation have an impression, also be I to Vue, further understanding.
  3. About source part, I also in learning at the same time, the main or prepare specific data driven and responsive to him to learn the core processing of parts, the Api series, of course, is also at the same time in the personal energy research sense, go back to the deep understanding of, if you are energetic enough, or never involved, I will find a corresponding release link I think good blog.
  4. This article is all personal to the content, I hope to see you, help, but also I on Vue learning a comb it.