This is the 14th day of my participation in the August More Text Challenge. For details, see:August is more challenging

When instantiating the VueRouter object, pass in the mode parameter as a constructor to determine the Router mode. The default hash mode is used. Use supportPushState to determine whether the History mode is supported. If the hash mode is not supported, the hash mode is rolled back. If the hash mode is not run in the browser, the abstract mode is forced. The route is instantiated based on mode and type. Initialize operations and listening by type. There are two methods exposed: push(),replace().

Hash mode:

The # on the path is used to indicate the location in the web page, and the # symbol followed by a character is called a hash. It can be read through the window.location.hash property. It has the following features: 1. It is not included in HTTP requests and is used to guide browser actions. Therefore, it is useless to the server. Changing the Hash will not reload the page. Window.addeventlistener (” hashChange “,funcRef,false) 3. Each time you change the Hash, a record is added to the browser access history.

Hash.push() push(location: RawLocation, onComplete? : Function, onAbort? : Function) {this.transitionTo(location, route => {// This method is used to handle route changes, parent class definition. pushHash(route.fullPath) onComplete && onComplete(route) }, OnAbort)} function pushHash (path) {window.location. Hash = path} transitionTo( transitionTo (location: RawLocation, onComplete? : Function, onAbort? : Function) { const route = this.router.match(location, this.current) this.confirmTransition(route, () => { this.updateRoute(route) ... }) } updateRoute (route: Route) { this.cb && this.cb(route) } listen (cb: }}}}}}}}}}}}}}}}}}}}}}}}Copy the code

When the plug-in is loaded, VueRouter’s install() method mixes in the Vue object, registers a mixin object globally by calling the vue.minxin () method, affects each Vue instance, mixes in the beforeCreated hook, Define the _route attribute through vue.util.definereactive (). When the _route value changes, the Vue instance’s render() method is automatically called to update the view. // This is the response behavior

$router.push() –> HashHistory.push() –> History.transitionTo() –> History.updateRoute() –> {app._route = route} –> Vm. render() // Route changes to the update process

Hash. The replace () / / function principle call replaceHash () / / window location. To replace the replace method

Monitor address bar

SetupListeners () {// Listen for routing changes in the address bar by adding an event, the rest of the response is the same as the Hash. window.addEventListener('hashchange', () => { if (! ensureSlash()) { return } this.transitionTo(getHash(), route => { replaceHash(route.fullPath) }) }) }Copy the code

The History mode:

The History interface is the interface provided by the browser History stack. It can jump through the back(),forward(),go() and other methods. And you can read the browser history stack. History provides two methods:

window.history.pushState(stateObject, title, URL) //pushState() window.history.replaceState(stateObject, title, URL)//replaceState()

StateObject: When the browser jumps to a new state, it triggers a popState event that carries a copy of the stateObject parameter. Title: Title of the added record URL: URL of the added record

Both methods change the URL, but do not immediately send a request for that URL. The logic of both methods is similar to that of hashing, except that the Hash assignment to history.pushState() and the replaceState() history mode add a listener to the browser address bar that is executed directly in the constructor:

constructor (router: Router, base: ? string) { window.addEventListener('popstate', e => { const current = this.current this.transitionTo(getLocation(this.base), route => { if (expectScroll) { handleScroll(router, route, current, true) } }) }) }Copy the code

The History mode requires browser version support.

Vue-router Summarizes the two modes

In addition to the browser interface, there is an abstract mode, which uses an array stack to simulate the browser history stack function. The hash mode is similar to the History mode except for a # navigation. The pushState() method has the following advantages: 1. The new URL set by pushState can be any URL of the same origin as the current URL. The Hash can only change the part after the #, so only the URL of the same document as the current URL can be set

2. PushState the new URL can be exactly the same as the current URL and the record will be added to the stack. The Hash must be different for the record to be added

PushState You can use the StateObject to add data of any type to records. Only short strings can be added to hashing

4. PushState Provides an additional title attribute for later use

One problem with the History pattern is that the user simply enters the address and presses Enter. The History pattern changes the URL, such as the normal request back end, without going through the index.html page, whereas the packaged request file usually needs to go through the index.html page to access it. If no corresponding processing is configured, a 404 error is returned. If you use the Hash mode and configure the path after packaging, you can directly load the Vue single-page application from the file system.

Vuex

1.State: Contains the states of the stores in the store.

Getters: Similar to the computed properties in Vue, the return value is computed based on other getters or states.

3. Mutation: a set of methods that change the state in the store.

4. Action: a set of methods that can contain asynchronous operations. An action is similar to a mutation in that it commits (calls) the mutation rather than directly changing the state. MapState 2. MapGetters 3. MapMutations 4. MapActions // The reason for the response of the auxiliary function method is that state is stored in the data of Vue instance components, Vuex getters use computed of VUE to monitor data in real time. Vuex implements state sharing between components by injecting store objects globally. Vuex is appropriate when multiple components automatically retrieve the changed data for business logic processing.

Vue Life cycle

With the exception of beforeUpdate/updated hooks, hooks are only executed once when they are initialized and destroyed.

BeforeCreate (): called after the instance is initialized and cannot access data or methods on data, computed, watch, methods. // Often used to initialize nonresponsive variables

Created (): When an instance is created, it has access to data, computed, watch, methods, and data, but is not mounted to the DOM, it has no access to the EL property, el property, EL property, ref property content is empty array. // Often used with simple Ajax requests, page initialization.

BeforeMount (): is called before the mount starts. BeforeMounted, the template is found and compiled into the render function. Mounted (): the instance is mounted to the DOM. In this case, the DOM node can be obtained using the DOM API. The $ref attribute can be accessed. // Often used to get VNode (class used to create DOM, different instances representing different types of real DOM) information and operations, Ajax requests.

Beforeupdate (): called when responsive data is updated, before the virtual DOM is patched, suitable for accessing the existing DOM before the update. // For example, manually remove added event listeners

Updated (): Called after the virtual DOM has been rerendered and patched, the component DOM has been updated. // You can perform operations that depend on the DOM, avoiding the possibility of getting stuck in an infinite loop by manipulating data in this hook function.

BeforeDestroy (): called before the instance is destroyed. At this step, the instance is still fully available, and this can still get the instance. // Common and destroy the timer, unbind global events, destroy plug-in objects and other operations.

Destoryed (): called after the instance is destroyed, everything indicated by the Vue instance is unbound, all event listeners are removed, and all child instances are destroyed.

Note: 1. The difference between Ajax in the created phase and Mounted requests: The created page view does not appear, and if there is too much information requested, the page will remain blank for a long time.

Mounted does not guarantee that all sub-components are mounted together. Call this.$nextTick() and wait until the view is rendered.

Life cycle of parent and child components:

1. The parent component is mounted only after the child component is mounted

2. When the child component is mounted, the parent component will execute the beforeUpdate/updated hook function (once).

3. Parent and child components are monitored separately during data changes, but data in update props is associated (practical).

4. The child component is destroyed before the parent component is destroyed