From the perceptual point of view, I was not bothered to use Vue, think the react kit used more comfortable, but the more to fire vue now, so also not into the Vue (Chowder) pit. Vue/anguarjs/react, the three-to-one relationship is now:
Https://www.zhoulujun.cn/uploadfile/images/2018/0626/20180626214906428779269.jpg
Own PS, feel deep and reasonable, Sao years of their own understanding, and then ask military elder brother ^_^
But return to the real question, see Vue or first understand the next https://cdn.zhoulujun.cn/vue.jpg (too big, oneself open)
Vue life cycle and related topic component instance cycles
The implementation of all the functions of Vue revolves around its life cycle, and invoking the corresponding hook function at different stages of the life cycle can realize two important functions of component data management and DOM rendering. Learning the life cycle of an instance can help us understand the operating mechanism of the Vue instance and make better use of the hook function to complete our business code.
The functions associated with create and mounted are:
Beforecreated "created" beforemount "mounted" Beforedestroy
Beforecreated:el and data are not initialized, case: You can add a loading event here and get the route parameters, but this. (data|computed|methods) parameters are Undefind ( cannot access the El attribute and data property, etc. )
Between Beforecreate and created: During this life cycle, the initialization event, the observation of the data, can be seen in the created when the data has been bound with Data property (the value of the property in data changes, while the view will change)
Created: The component instance is created, the property is bound, but the DOM has not yet been generated, $el property does not yet exist (this. $refs. xxx===undfined). Case: At this end of loading, there are also some initializations, such as calculating the current component data based on the parent component props
Between created and Beforemount: First, you will determine if the object has an El option. If something continues to compile down, if there is no El option, stopping the compilation also means stopping the lifecycle until the VM is called on the Vue instance. $mount (EL). Again determine if the template parameter option is available ( because Vue needs to find the corresponding outer template via El):
(1) If the Vue instance object has the template parameter option, it is compiled as a template into the render function.
(2) If there is no template option, the external HTML is compiled as a template.
(3) You can see that the templates in the template take precedence over outer HTML.
If there is no template, it is compiled with the createelement of the render descendant
Overall ranking priority: Render function Options > Template Options > Outer HTML.
There's nothing to see here. Official documentation Standalone build and run-time build
Beforemount: Completed El and data initialization. Pit: If the MSG data is not compiled into {{msg}} at this moment, the user can see the {{msg}} V-cloak for the moment if the {{msg}} is used directly during the life cycle Beforemount
Between Beforemount and mounted: Adds a $el member to the Vue instance object and replaces the hanging DOM element
Mounted: Complete mount case: In this initiating back-end request, take back the data, with the routing hooks do something
BeforeUpdate: Can hear the change of data but the view layer has not been re-rendered, the view layer of data has not changed
Between BeforeUpdate and update: When Vue discovers that data has changed, it triggers a re-rendering of the corresponding component (re-renders the virtual DOM, and updates the real DOM with the diff algorithm to compare the Vnode node differences) (Virtual DOM Re-render and patch), successively call beforeUpdate and updated hook function (beforeUpdate: Can hear the change of data but the view layer has not been re-rendered, the view layer data has not changed, updated: The view layer is re-rendered and the data is updated. Here you can review the following react on the update function.
Updated: Wait view layer is re-rendered, data update
Beforedestroy components destroyed before the case: Are you sure to delete xx? The second: such as merry text, after the routing jump, because the component has been destroyed, but SetInterval has not been destroyed, still in the background call, the console will continue to report errors, if the calculation of large words, can not be cleared in time, will lead to serious page lag. Workaround: Beforedestroy stop setinterval in the component life cycle
Destroyed: The current component has been deleted and the relevant content is emptied. After the instance has been destroyed, the DOM and attribute methods are still there, but the changes will no longer take effect!
Here, by the way, review the React life cycle .
Getdefaultprops () +getinitialstate () Es5≈es6 contruct ()
Function initialization. Timed init state, also access to props. This phase is equivalent to what Vue's create function should do.
Componentwillmount ()
Component initialization is only called, and later component updates are not called, the entire life cycle is called only once, and the client is on the server, at which point the state can be modified. This phase should be equivalent to Vue's Beforemount ()
Render ()
React the most important steps, create a virtual DOM, perform a diff algorithm, and update the DOM tree here. You cannot change the state at this time. This is the equivalent of Vue mounted
Componentdidmount () ()
The component is called after rendering, only once, only at the client. At this stage, the general asynchronous data is placed within this function to process
Componentwillreceiveprops (Nextprops)
Called when component initialization is not called when the component accepts a new props.
Shouldcomponentupdate (Nextprops, Nextstate)
React is a very important part of performance optimization. When a component accepts a new state or props, we can set whether two props and states are the same before and after this comparison, and if the same, return false to prevent updates, because the same property status will certainly generate the same DOM tree, This makes it unnecessary to create new dom trees and old dom trees to compare diff algorithms, saving a lot of performance, especially when the DOM structure is complex. But state will remain updated.
This here, is the focus of Vue PK react.
Vue claims to be able to calculate the differences of the virtual DOM more quickly, because it keeps track of the dependencies of each component during the rendering process and does not need to re-render the entire component tree.
For react, all subcomponents are re-rendered whenever the state of the app is changed. Of course, this can be controlled by shouldcomponentupdate This life cycle approach, but Vue treats this as the default optimization.
Summary: Using virtual Dom is a good idea if your application has complex interactions and needs to handle a lot of UI changes. If you do not update the elements frequently, then virtual DOM does not necessarily apply, and performance is probably not as straightforward as manipulating the DOM.
Componentwillupdata (Nextprops, Nextstate)
The component is not called when it is initialized and is called only when the component is about to be updated, and the state can be modified. This is not normally used for living eggs. Maybe toast a bit. Roughly equivalent to Vue's beforeupdate.
Componentdidupdate ()
When the component is initialized, it is called when the component Update is complete and the DOM node can be obtained.
Componentwillunmount ()
The component will be called when it is unloaded, and some event listeners and timers need to be cleared at this time. The equivalent of Vue's Beforedestroy
In contrast, the react life cycle is more refreshing. Suggestion: Re-talk about react advantage--react Technology Stack Review
Routing hooks
Routing is the focus of the project, and many things can be done in the routing. Planning project infrastructure at the core of routing and store, without good planning, engineering is a piece of crap.
Global Routing Hooks
Acts on all routing switches, typically defined inside main.js
Beforeeach: Typically in this hook callback, the route is intercepted. For example, a user who is not logged in will go directly to a page that needs to be logged in to be visible, then you can use next (false) to intercept it, to jump back to the original page, and so on, it is worth noting that if the next method is not called, then the page is stuck there.
Four ways to use next
Next () jumps into the next page
Next ('/path ') changes the direction of the route, causing it to jump to another route
Next (false) returns to the original page
Next ((VM) =>{}) is only available in Beforerouteenter and the VM is a component instance.
Aftereach: Called at the end of all routing jumps, and Beforeeach is similar, but it does not have next method, here like to do the change tag title: Document.title = To.meta.title and so on.
Component Routing Hooks
Unlike global hooks, it only works on a component and is typically defined in the. vue file.
Beforerouteenter
This is a very different hook. Because Beforerouterenter is called before a component is created, it cannot access the component instance directly with this.
To make up for this, the Vue-router developer, who adds a stunt to his next method, can pass a callback, and the first parameter of the callback is the component instance.
In general, we can make use of this to modify the data on the instance to invoke the method on the instance.
We can request the data in this way, after the data has been obtained, and then call next to ensure that you enter the page, the data has been obtained. Yes, next here has a blocking effect. If you don't call it, you'll always be stuck there.
Beforerouteleave
Called when it leaves the route. You can use this to access a component instance. But next cannot pass the callback.
Beforerouteupdate:
This method is added with the vue-router2.2 version. Because the original version, if a jump between two sub-routes, is not triggered beforerouteleave. This causes some reset operations, which are not triggered anywhere. Before, we all hack with watch $route. But through this hook, we have a better way.
Instruction Cycle
Bind: Called only once, when the instruction is first bound to an element, this hook function allows you to define an initialization action that is performed once at bind time.
Inserted: Called when the bound element is inserted into the parent node (the parent node exists to be called and does not have to exist in document).
is actually called when inserting a vnode.
Update: Called when the template that contains the binding element is updated, regardless of whether the binding value changes. You can ignore unnecessary template updates by comparing the binding values before and after the update.
Use caution, if the event is bound in the instruction, and use this cycle, remember to log off the event
Componentupdated: Called when the template on which the binding element is completing an update cycle.
Unbind: Called only once when the instruction is unbound from the element.
A page jump, something that happens
Route hooks (Beforeeach, Beforerouteenter, Aftereach)
Root components (beforecreate, created, Beforemount)
Components (beforecreate, created, Beforemount)
Command (BIND, inserted)
Component mounted
Root component Mounted
Beforerouteenter's next callback.
Nexttick
Conclusion:
Route hooks are executed very early, even before the root instance is rendered
Specific order Router.beforeeach > Beforerouteenter > Router.aftereach
Tip: Avoid using methods or properties inside the instance when routing interception.
In the development of the project, we have a pat on the forehead, the specific interception of the program, written in the root instance of the method, to Beforeeach to call. As a result, the entire interception cycle is deferred until the instance is rendered.
As a result, the requests in the beforerouteenter of some routing components cannot be intercepted, and the page seems to have been intercepted.
Actually the request is still sent out, and the function inside the beforerouteenter is still executed.
The binding of the directive before the component mounted, after the beforemount of the component
Have to mention that Beforerouteenter's next hook
The execution order of Beforerouteenter is so forward, and the function of the callback hook of next, the execution is very much behind, after mounted!!
We usually load some first-screen data in the Beforerouteenter, and when the data is received, the next hook is called, and the data is bound to the instance by the callback's parameter VM.
Therefore, please note that Next's hook is very back.
Nexttick: The sooner a Nexttick is registered, the earlier it is triggered
The above mentioned so many router, homeopathic summary under:
Router-link Property
: To: Equivalent to the "Herf" attribute in the A tag, followed by the jump link
Replace:replace when added to the Routre-link tab, no history is left when the page is toggled
Tag: The router-link with the tag attribute will be rendered as the corresponding label
Active-class: This property is the class property that is set when the link is activated, that is, all links to the current page are added to the class attribute
Exact: The strict mode of opening Router-link
With the Vue-router, to prove that the project is still quite large, it is recommended to use VUEX to do global data management (may use the Redux habit!) )
Vuex the modular demolition of the store
Vuex's store is inherently self-modules, and requires thunk middleware, which handles asynchronous data. Copy a little of my Project code demo below:
Const STORE = new Vuex.store ({modules: {authform:authformstore, Bankadd:bankaddformstore}});
Here is a demonstration of the store
const authformstore = { state: { name: "" }, mutations: { update: function (State, obj) { //I used to write n more than one update function, pattern Tucson broken state[obj.name] = Obj.value; }, }, action: { setdata: function (context, obj) { //TODO vue.http.post ("API", params, {emulatejson: true}). Then (function (RES) { // Processing Business // call above Setagree method update point likes context.commit (Obj.name, obj.value); }, function () { })     },&NBsp; }, getters: { getnews (state) { //todo return new value } }}
In the Vue component Mapstate
Computed: {membertype:function () {Let membertype = this. $route. Params.membertype; This.initwechat (Window.location.href, membertype); return membertype; }, ... mapstate ({authform:state = state.authform, epcerttype:state = State.authForm.epCertType})},
Here's a pit: when the V-model property value of the form is Vuex state, if strict mode is in place, V-model attempts to modify the value of V-model because the modification is not mutation executed, and the error is thrown in strict mode.
In this case, there are two ways to do this: one is a computed property of two-way binding, one is to bind the form to value, and then listen for the input or change event to invoke action in the event.
computed:{message:{Get () {return this. $store. Obj.message}, set (value) {this. $store. comm It (' Updatemessage ', Value)}}
The second method of
computed:{mapstate ({message:state = state.obj.message})},methods:{Updatemessage (e) {this. $store. Commit (' Updatemessage ', e.target.value)}}mutations:{//store mutation function updatemessage (state,message) {state.obj.message= Message}}
The core functions of Vue.js are two, one is the response type data binding system, the other is the component system
The so-called bidirectional binding refers to the fact that data in the Vue instance is consistent with the content of its rendered DOM element, and the other party updates the same data accordingly, regardless of who is changed. This is done by setting the property accessor.
Data binding on Vue\angluar\react: two-way binding and unidirectional data flow
Vue's dependency tracking is "principle does not support bidirectional binding, V-model just through listening DOM event implementation of syntax sugar"
Vue's dependency tracking is achieved by object.defineproperty all the properties of the data object into Getter/setter, and when a property value is changed, the set function is triggered, and the get function is triggered when the property value is obtained. This feature is used to change the view when the data is changed, that is, only when the data changes to trigger the view changes, in turn, in the operation of the view, only through DOM events to change the data, and then change the view, so as to achieve two-way binding
Two-way binding is within the same component, data and views are bound together, and the communication between parent and child components is not related;
Communication between components is a one-way data flow for better decoupling between components, and in development there may be multiple subcomponents that depend on a parent component's data, and if the child component can modify the parent component data, a subcomponent change will cause all dependent subcomponents of this data to change. So Vue does not recommend subcomponents modifying the parent component's data, and modifying props directly throws a warning
It is recommended to read the implementation principle of vue.js two-way binding
React No data bidirectional binding
React is a one-way data stream: Any variable data should have only one single "data source" and the data source State promoted to the parent component
In the react, the state (model layer) and the view layer data are bound to the real-time update of the data, in particular, the view layer directly write the JS code in the model layer of data to render, once like form operations, triggering events, Ajax requests and other triggering data changes, then double-sync
Angular is also two-way data binding (all data changes are done at once and then applied to the interface as a whole)
Under Amway: A further discussion on ANGULARJS data binding mechanism and its underlying principle-angularjs FAQ Summary
Among the three, I still prefer React+redux mode (top-down data flow, business focus on data tree design)
It is necessary to mention that Vuejs has encapsulated the native method of the array in data, so that it can trigger the view update when changing the array. I'm having a lot of pits when I write date controls, like:
Modify the elements of an array directly by index, for example vm.items[0] = {title: ' title '}
Cannot directly modify the length of an array, for example vm.items.length = 0
Solution: For the first Vue, the Set method Vm.items.set (0,{title: ' title '}) or VM is provided. $set (' items[0] ', {title: ' title '}). Another way to render a list is to have a performance tip: If the array itself has a unique identity ID, then at render time, the array is given a unique identity by trace-by, so that Vuejs will try to repeat the scope and DOM elements of the original object during the rendering process.
about using the "arrow function to refine your Vue module" (recommended click to read), streamlined is:
Methods: {method () {//todo}//Not: Method: () =>{//todo} method:function () {//todo}}
Reference article:
The path of Vue2.0 exploration--some understandings of life cycle and hook function
Detailed Vue life cycle
Vue Life cycle
Vue Life cycle Exploration
Vue installation, router-link some properties, usage, tag active-class,to,replace,exex, etc.
Modular split practice for Vuex Store
A comprehensive comparison between vue.js and react
Vue.js 2.0 source parsing of the front-end rendering Chapter
Use the arrow function to refine your Vue module –dotdev
Reprint Please indicate source,vue2.x into pit summary-review contrast Angularjs/react-vue into pit summary - Zhou Lujun's personal website ,:https:// Www.zhoulujun.cn/html/webfront/ECMAScript/vue/8125.html. The wrong place, hope to tell, thank you!
vue2.x into the pit summary-review contrast Angularjs/react's unified