Talking about the process of VUEX injection Vue life cycle

This article is the 13th article of [Front End Dictionary] series of articles, the next 9 I will surveillaarize Vue, I hope that these 9 articles can deepen the understanding of Vue. Of course, the premise of these articles is that you have a certain basis for Vue for VUE. If there is no foundation, it is recommended to see the official document first.

First article I combine some source code of Vue and Vuex to illustrate the process of Vuex into the Vue lifecycle.

Speaking of the source code, actually not imagined. Also similar to our usual write business code, all of which are calls. But the source code call tree will be more complicated.

Why use Vuex

We cannot encounter data or status of components. The application’s business code is gradually complex, the drawback of the props, events, event bus, etc. will be more obvious. At this time, we need VUEX. Vuex is a status management tool specifically designed for VUE.

Status Management is an important means of decoupling of VUE components.

It draws on the basic idea of ​​FLUX, Redux, and extracts the status to the overall situation to form a Store.

VUEX does not limit your code structure, but it is necessary to comply with some rules:

浅谈Vuex注入Vue生命周期的过程

The status of the application hierarchy should be concentrated in a single Store object

Submiting MUTATION is the only way to change the status, and this process is synchronized
  • asynchronous logic should be encapsulated into the action
  • Vuex injection Vue life The process of cycle

When we install the plug-in, we will always load the plugin like the Vue.use () , but

vue.use ()

What did you do? Import Vue from 'Vue'; Import Vuex from 'Vuex'; Vue.Use (Vuex);

  Vue.use () What did  
Install the Vue.js plugin. If the plugin is an object, an install method must be provided. If the plugin is a function, it will be used as the install method. When the install method is called, VUE is incorporated into parameters.

The above is the explanation of the official documentation. Next, we have seen from the source section

vue.use ()

.

VUE source code is called in

Initglobalapi

inlet method, this method is defined vue.use () need to do Content.

Function INITGLOBALAPI (VUE) {... Inituse (Vue); Initmixin $ 1 (VUE); // Telling Vue.Mixin will mention .. ....} function inituse (vue) {vue.use = function (plugin) {var installedplugins = (this._installedplugins || (this._installedplugins = [])); / * Judging whether this plugin has been installed * / IF (installedPlugins.indexof (plugin)> -1) {return this} var args = TOARray (arguments, 1); args.unshift (this); / * Judgment the plugin has install method * / if (typeof plugin.install === 'function') {Plugin.install.Apply (plugin, args); Else if (TypeOf plugin === 'function') {plugin.apply (null, args);} installedplugins.push (plugin); returni};} This code mainly did two things:

one is to prevent the same PLUGIN
  in the same is to initialize Plugin  
Install method

    After reading the above source, we know that the plugin (Vuex) needs to provide a
  1. Install
  2. method. Then let’s see if there is this method in the VUEX source code. As a result, it is of course:
  3. / * Exposed INSTALL method * / function install (_VUE) {/ * avoids repeated installation (Vue.use can also detect Whether the same plugin is repeatedly installed) * / if (Vue && _Vue === VUE) {{Console.Error (‘[Vuex] Already Installed. Vue.use (Vuex) Should Be Called Only Once.’);} Return } Vue = _VUE; / * Confused Vuexinit into VuE’s Before2.0 (Vue2.0) or _init method (Vue1.0) * / ApplyMixin (Vue);}

This code mainly did two things:

One is to prevent Vuex from being repeatedly installed

Another one is to perform
ApplyMixin , the purpose is to implement
 Vuexinit  method to initialize VUEX  
ApplyMixin (Vue)
Source:

/ * Confusing Vuexinit into the Vue BEFORECREATE * / function applymixin (vue) {var version = number (Vue.Version.split (‘.’) [0]); if (Version> = 2) {Vue.Mixin ({BeforeCreate: Vuexinit});} else {/ * Vue1.0 processing logic, omitted * / …} function vuexinit () {…}}
  1. from above The source code, you can see that Vue.Mixin method will be confused in Vuexinit
  2. method into
BeforeCreate

hook, it is also because of this operation, so each VM instance will call [ Vuexinit method. So Vuexinit

what did you do?
vuexinit ()
   WeWhen using Vuex, you need to pass the Store in the Vue instance. 
New Vue ({EL: ‘#App’; “

But we are in each The Store can be accessed in a VM, which needs to be rely on Vuexinit . Function Vuexinit () {const options = this. $ Options if (options.Store) {/ * Root node is Stroe * / this. $ Store = typeof options .Store === ‘function’? Options.Store (): options.store} else if (options.parent && options.parent. $ store) {/ * subcomponents Get the $ store directly from the parent components, this is guaranteed All components are public in the same store * / this. $ Store = Options.parent. $ Store}}

When the root node is StroE, it will be directly Options.Store

assigned to

this. $ Store

. Otherwise, it will be noted that it is not a root node to get from the parent node
$ Store .
 With this step, we will access the Store instance in any of the VMs through this. $ Store. Next, we will say Vue.Mixin ().   Vue.Mixin () 
Global registration a mix, affecting all Vue instances created after registration. The plug-in authors can use mixed to inject custom behavior to components.

Not recommended in application code. Initglobalapi

Initglobalapi
Initmixin $ 1 (Vue) method:
   
Function INitmixin $ 1 (Vue) {vue.mixin = function (mixin) {this.Options = MergeOptions (this.Options, mixin); returni};}

The process of Vuex injection Vue life cycle is like this. If you are interested, you can look at the source code of Vuex directly, then let's talk about the Store. STORE The above talked

Vuexinit

got the Store from Options. So what is the STORE coming next?

We will define a Store instance below when we use VUEX.

Import Vue from ‘Vuex’Import Vuex from’ Vuex’Import Mutational from ‘./mutations’vue.use (Vuex) Const State = {ShowState: 0,} Export Default New Vuex.Store ({Strict: True, State, GetterS,}) Do not enable rigorous mode in the publishing environment. Strict mode depth monitoring status tree to detect non-compliance status changes – please ensure that stringent mode is turned off in the publishing environment to avoid performance loss.

State’s Response Do you care about how State can respond? This is mainly implemented by the RESETOREVM (THIS, STATE, STATE)

method called in the STORE constructor.
This method is mainly to reset a private _vm (an instance of Vue). This _vm object will keep our Store tree and store the Store’s getters by computing properties. Now look at its implementation process.
  / * Use VUE internal response STATE * / FUNCTION RESETSTOREVM (Store, State, HOT) {/ * Store VM Objects * / Const Oldvm = Store ._vm store.getters = {} const wrappeteters = store._wrappedget hands const compute = {} / * Defines the GET method for Store.DefineProperty method. When calling this. $ Store.getters.xxx, it will visit Store._VM [XXX] * / FOREACHVALUE (WrappedTers, (FN, Key) => {computed [key] = Partial (FN, Store ) Object.defineproperty (sTore.getters, Key, {Get: () => Store._VM [key], enumerable: true // for local getters})}) const sameent = vue.config.silent / * Setting Silent for TRUE is to Cancel _vm all logs and warnings * / vue.config.silent = true / * here new has a Vue object, using the response implementation of the Vue internal response STATE and computed * / store._vm = new vue ({data: { $$ State: State}, computed} Vue.config.silent = Silent / * Enables strict mode, Vuex's modification of State can only be * / if (store.strict) {EnableStricTmode in the Mutation's callback function (Store " )}} f (oldvm) {/ * Release the old VM State reference, and destroy this old _vm object * / if (hot) {store._withcommit (() => {OldVM._Data. $$ state = null })}} => Oldvm. $ Destroy ())}}  
The response type of State is probably implemented, that is, the initialization resetstorevm method the process of.

Take a look at the Store’s commit method

We know that the commit method is used to trigger Mutation.

commit (_type, _payload, _options) {/ * unifyObjectStyle method of correction parameter * / const {type, payload, options} = unifyObjectStyle (_type, _payload, _options) const mutation = {type, payload} / * find the corresponding Mutation method * / const entry = this._mutations [type] if (! Entry) {if (process.env.node_env! == 'production') {Console.Error (`[Vuex] Unknown Mutation Type: $ {TYPE } `)} Return} / * Method in Mutation * / this._withcommit (() => {entry.Fore (Function Commititerator (Handler) {handler (payload})} / * Notify all subscribers, pass Enter the current Mutation object and current state * / this._subscribers.Foreach (Sub => SUB (Mutation, this.State)))))))) = == Products' && Options && Options.silent) { Console.warn (`[Vuex] Mutation Type: $ {type}. Silent Option Has Been Removed.` + 'Use the filterFunctionality,}

The method first performs a parameter style check, and then uses the
 _withcommit  method to perform this batch trigger [ Mutation  Processing function. After the execution is complete, notify all 
_SUBSCRIBERS (Subscription Functions) The
Mutation

object of this operation and the current

State

state. The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment