32

It’s almost the end of the year, and many small partners may choose to change jobs or get promoted or have an assessment. The interview is especially important. During the interview, the interviewer will always ask some basic content to examine our mastery of professional knowledge. Then decide whether to hire.

Preface

Now for the front-end, the most asked questions may be the JavaScript . In addition, the most asked questions are some knowledge points related to the current mainstream framework. At present, the mainstream framework is Vue、React、Angular . In terms of the domestic Internet situation, it is still Vue .

At present, there are more and more interviews, which are not the same as the previous interviews. Two or three years ago, they asked more about the application of mainstream frameworks. At present, they are more about the underlying questions. To summarize and record these Vue Hope to help more friends.

Basic interview questions

The basic Vue questions are 061938f41cf181 application and usage interview questions. Most of this part is for junior engineers and is relatively simple.

Q: What are the lifecycle hooks of Vue?

A: Vue life cycle of a total of 10 months:

  1. beforeCreate-Called before the instance is initialized, this does not exist in this life cycle, because the Vue instance has not been created yet.
  2. created-called after the instance is initialized
  3. beforeMount-is called before the start of the mount. If it is not called during server-side rendering, because the element has not been rendered yet, the DOM element cannot be obtained during this life cycle.
  4. mounted-is called after mounting, it is possible to get elements and perform operations
  5. beforeUpdate-Called before the view layer data is updated. Before the virtual DOM updated, the DOM j node can be obtained, but this node is the DOM node before the update
  6. updated-Called after the view layer data is updated. The DOM node obtained here is 061938f41cf3dc after the DOM
  7. beforeDestroy-called before the instance is destroyed, in the destroyed component
  8. destroyed-called after the instance is destroyed

beforeDestroy and destroyed life cycle phases can be used in this phase to `Vuex data of 061938f41cf463, cancel event monitoring and other operations to improve performance.

The above are the more commonly used life cycle hook functions, and there are two more special life cycle hooks, namely activated and deactivated . These two life cycles will only be executed after keep-alive

  1. activated-used when an instance is activated. When repeatedly activating an instance, the life cycle will be mounted after 061938f41cf4d8.
  2. deactivated-when the instance is not activated

Question: The execution order of the life cycle hook functions of the parent component and the child component?

answer:

Vue execution order of the life cycle hook functions of the parent and child components of 061938f41cf552 can be classified into the following 4 parts:

Load the rendering process
  1. Parent beforeCreate
  2. Parent created
  3. Father beforeMount
  4. Child beforeCreate
  5. Child created
  6. Sub beforeMount
  7. Mounted
  8. Parent mounted
Sub-component update process
  1. Parent beforeUpdate
  2. Sub beforeUpdate
  3. Child updated
  4. Parent updated
Parent component update process
  1. Parent beforeUpdate
  2. Parent updated
Destruction process
  1. Parent beforeDestroy
  2. Sub beforeDestroy
  3. Subdestroyed
  4. Parent destroyed

Q: In which life cycle is the asynchronous request called?

answer:

It can be called in the hook functions created , beforeMount , mounted , because in these three hook functions, data has been created, and the data returned by the server can be assigned. It is recommended to call the asynchronous request in the created hook function, because the asynchronous request is called in the created hook function, because the server data can be obtained faster, and the page loading time ssr does not support beforeMount and mounted hook functions, so there are created Contribute to consistency.

Question: Can the parent component monitor the life cycle of the child component?

answer:

Yes, there are two ways to do it. The first is to use the $emit custom event for event monitoring, and when the sub-component executes to a certain life cycle, use $emit notify. The second method uses @hook: life cycle name. The @hook method can not only monitor mounted , but other life cycle events, such as created , updated , etc. can also be monitored.

Q: What does keep-alive do?

Answer: keep-alive is a Vue , which can keep the state of the included components and avoid re-rendering. It has the following features:

  1. Generally used in conjunction with routing and dynamic components for caching components
  2. Provide include and exclude attributes, both support strings or regular expressions, include means that only components with matching names will be cached, exclude means that any components with matching names will not be cached, and exclude a higher priority than include
  3. Corresponding to the two hook functions activated and deactivated , when the component is activated, the hook function activated is triggered, and when the component is removed, the hook function deactivated .

Q: What are the value-passing communication methods between components?

Answer: There are 7 ways of communication between components:

1. props/emit

The parent component passes in the attributes, and the child component props . The parameters passed in by the parent component can be obtained in this way. The child component can $emit('time name', parameter), listen to the event in the properties of the parent component, and also get the parameters passed by the child component, using v- on: event name=func or name=func to monitor custom events of sub-components.

You can also use prop receive the function as a parameter. The child component calls this function. When the child component executes the function, it can pass in the corresponding actual parameter. When the parent component receives it, it will receive it in the form of formal parameters and execute the corresponding logic to achieve communication. Purpose.

2. EventBus

EventBus also known as the event bus, and EventBus can be used as a communication bridge to enable communication between any two components, just as all components share the same event center, which can be registered to send events or receive events.

How to use EventBus , use new Vue to obtain the Vue instance, in essence, EventBus is a component that does not have DOM , it has only its instance method, so it is very portable.

You can get to Vue instance to mount Vue.prototype can also be stored in a separate js file export, depending on the circumstances of which the business use is generally recommended to use the second method.

Use EventBus.$emit("event name", parameter); to publish events. Use the EventBus.$on("event name", func) method to subscribe to the event. func the parameter passed by the corresponding event.

EventBus is to save the registered event and call it when the event is triggered. Define a class to handle events.

3. Vuex state management

Vuex is Vue core plug any communication for any of its components, the need to pay attention to possible refresh Vuex data will be lost.

Create a globally unique state management warehouse store , with synchronous mutations , asynchronous actions to manage data, cache data getters , can be divided into various modules modules easy to maintain

4. ($parent|$root)/$children

This communication method is recommended, which will make the two components strongly coupled together, which is not particularly friendly for future maintenance and expansion.

Obtain the corresponding component instance through ($parent|$root)/$children , and call the internal method of the component to achieve the effect of communication.

5. $ref

Get the child node by $ref , which is often used by the parent component to call the method of the child component. In $refs can store all the current ref . In the instance, you can call the internal method of the component.

6. attrs/listeners

$attrs can get the attributes passed in by the parent component but not props , and you can use v-bind="$attrs" to continue to pass parameters to the child component.

$listeners will expand all the monitored events of the parent component. The click event trigger method of two components in a page is the same. You can use v-on="$listeners" to continue passing events to subcomponents.

7. provide/inject

The parent component uses provider to provide variables, and then the child component uses inject to inject variables. As long as it is called in the parent component, all the child components can call inject to inject the value in the parent component during the life cycle of the parent component.

Q: What is the difference between watch and computed?

answer:

computed is a calculated attribute that is similar to the data attribute in the data watch is used to monitor the change of a certain attribute. computed good at one data being affected by multiple data, but watch is used to monitor a certain one. Change of attributes.

computed supports caching only if the dependent data changes before recalculation. computed based on their responsive dependence, which is based on the value obtained by calculating the data props data or passed by the parent component watch Caching is not supported, and data changes will directly trigger the corresponding operation. watch receives two parameters, the first parameter is the latest value; the second parameter is the value before input;

computed does not support asynchrony, and it is invalid when there is asynchronous operation in computed watch supports asynchrony.

computed is used, the computed is a function, then the get will be taken by default. The return value of the function is the attribute value of the attribute. The attribute of in computed has a get and a set method. When the data changes, call set method. watch In use, the monitor data must be data the declared parent component or the passed props data, when the data changes, to trigger other actions, function has two parameters. immediate (component loading immediately triggers the execution of the callback function), deep (deep monitoring) In order to find changes in the internal value of the object, it is used when complex types of data are used.

computed is implemented internally based on Object.definedProperty() computed cache function, and the dependent value will not be recalculated if it does not change. watch is the monitoring value change. When the value changes, the corresponding callback function will be executed. computed and watch are executed based on the Watcher class. computed cache function of 061938f41d034a relies on a variable dirty , which indicates whether the value is dirty or not. The default false true , it is 061938f41d034f. When the value is dirty again, 061938f41d0351 or false directly returns the previous value.

Question: Why must data be a factory function and not an object?

answer:

Because of the Vue component reuse principle, because the data object is a reference type, when the data of one component changes, the state of another component will be affected, but returning the object in the form of a factory function will not cause such a problem, because each factory The object returned by the function is a brand new object relatively independent.

Q: Does style scoped work in Vue?

answer:

On the style tag in the vue file, there is a special attribute: scoped . When a style tag has the scoped attribute, its CSS style can only be applied to the current component, that is, the style can only be applied to the current component element. Through this attribute, the styles between components can be made not to pollute each other. scoped will add a unique tag data-v-something DOM structure and the css style, that is, CSS with an attribute selector to complete a similar scope selection method, so as to achieve style privatization without polluting the global effect. scoped is convenient to use, we need to use it with caution, because when we need to modify the style of public components (third-party libraries or project-customized components), scoped often causes more difficulties and requires additional complexity. Use >>> to penetrate the scoped and modify the style of other third-party components. Use sass or less to penetrate /deep/ .

Q: What is the difference between v-show and v-if?

answer:

v-if is true conditional rendering, because it will ensure that event listeners and subcomponents in the conditional block are properly destroyed and rebuilt during the switching process. v-if is lazy: if the condition is false at the time of initial rendering, nothing will be done ——The conditional block will not be rendered until the condition becomes true for the first time. v-show much simpler - no matter what the initial conditions, the elements will always be rendered, and simply based CSS of display property switch. Therefore, v-if suitable for scenes that rarely change conditions during runtime and do not need to switch conditions frequently, and v-show is suitable for scenes that require very frequent switching of conditions.

Question: When the object or array data in the data changes, what is the reason why the data has no view and does not respond?

answer:

Because Vue during initialization, will data data using object.defineproperty data sandwiched by get/set operation data in response to completion of the addition the properties, in Vue the property does not exist in the initialization data in the property is not so It was held hostage to unable to execute get/set . Vue provided the this.$set method to complete the data response to the newly added data.

Q: What is the difference between SPA and SSR

answer:

SPA application is now the most commonly used form of development, that is, the single-page application. The page is javaScript , which is called client-side rendering CSR . SPA rendering accessed by the client URL sends a request to the server, returns HTML structure (but SPA returned HTML structure is very small, only a basic structure). After the client receives the returned result, it starts to render HTML on the client, executes the corresponding javaScript JavaScript rendering, and finally HTML . After the rendering is completed, it sends a data request to the server again. Note that the data request is here, and the server returns json format data. . The client receives the data and then completes the final rendering.

SSR rendering process is like this. The client sends a URL request to the server. The server reads the template information of the URL HTML and data on the server. After the rendering is completed, it returns the HTML structure, and the client takes it at this time. HTML structure of the first screen page. So the user will be very fast when browsing the first screen, because the client does not need to send the ajax request again. It’s not that SSR Our page doesn’t belong to the SPA application anymore. It is still a separate SPA application.

SSR is CSR and SPA applications. When the first screen is rendered, the rendering is made on the server side. Note that it is only the first screen. Other pages still need to be rendered on the client side and received on the server side. After the request and the first screen page is rendered, it will carry the remaining routing information and reserve it for the client to render other routing pages.

SSR advantages:

  1. Better SEO, search engine crawlers can directly view the fully rendered page
  2. A wider content reach time ( time-to-content ), when the right requests the page, after the server finishes rendering the data, the rendered page is sent directly to the browser for rendering. The browser only needs to parse html does not need to parse javaScript .

SSR disadvantages:

  1. Development conditions are restricted, and certain life cycle hook functions of the Vue
  2. The development environment is based on Node.js
  3. Will cause more load on the server. Rendering a complete application in Node.js will obviously take up CPU server than just providing static files 061938f41d0899. Therefore, if you are expected to use it under high traffic, please prepare a responsive service load and adopt a caching strategy wisely.

Q: How many modes does vue-router have?

answer:

vue-router three common modes: hash , history and abstract .

Hash mode:
  1. hash value of url is # and the following part in 061938f41d0987
  2. hash value changes will not cause page refresh
  3. hash change the value of the trigger hashchange event
history mode:
  1. Use history.pushState to complete the url jump without refreshing the page
  2. Background configuration support is required. If URL not match any static resources, the server should return to the index.html page that the application depends on
abstract mode:
  1. Applicable to all JavaScript environments, for example, use Node.js
  2. Without a browser API , the router will automatically be forced to enter this mode
  3. The main purpose of this history record is to process SSR and replace this position with the start position by calling router.push or router.replace

Q: What is the difference between $route and $router?

answer:

$router

router Vue through the Vue.use(VueRouter) and 061938f41d0b3b constructors. This object is a global object, which contains all routes, contains many key routing information, as well as routing jump methods, hook functions, etc.

$route

$route is a redirected route object. Each route will have a $route object, which is a partial object. You can get the corresponding name , path , params , query etc. The attributes of the routing object are read-only, and the attributes inside are immutable (immutable), but you can use watch monitor routing changes.

Q: What are the guards of vue-router?

answer:

vue-router guards are divided into three types of guards: global guards, routing guards and component guards

Global guard

The literal understanding of the global guard is defined in the global hook function. When the route triggers a jump operation, the corresponding hook function will be triggered. There are three types of global guards:

  1. beforeEach: It is triggered before each navigation route jump
  2. beforeResolve: Triggered after component and the asynchronous routing component are resolved
  3. afterEach: Triggered after the route jump is completed

beforeEach global front guard receives three parameters:

  • to: the target routing object that is about to enter
  • from: The route object that the current navigation is about to leave
  • next: Be sure to call this method or it will block routing

Let me focus on the parameter next next is a function, and it does not need to be added, but once it is added, it must be called once, otherwise the route jump will stop. next parameter only beforeResolve two routing guards beforeEach and afterEach has already jumped to the target route and does not provide the next method. If direct execution next functions will be connected directly to target corresponding to the route. next(false) will terminate the current route and return to the route corresponding to the route form next jump scheme in 061938f41d0d0b (such as: next('/') or next({ path:'/'}) ), and it will jump to the corresponding address. next(error) then the navigation will be terminated, and the error will be passed to the callback registered by router.onError() beforeEach than one 061938f41d0d0f can be defined, which will be called according to the creation order, and the navigation is waiting until all guards are completed.

Routing guard

Routing guard only a beforeEnter , needs to be defined in the routing configuration beforeEnter guard, this guard is only triggered when entering the route, in beforeEach immediately after the execution, not in params , query or hash trigger change, beforeEnter routing guard parameters are to , from , next , same as beforeEach .

Component guard

Component guards need to be defined in the components. There are three types of component guards:

  1. beforeRouteEnter: routing calls before entering the assembly, the hook guard in the global beforeEach and routing guard beforeEnter after global beforeResolve and global afterEach called before, access instances less components within the guard, which is this as undefined , that he beforeCreate life Trigger before cycle
  2. beforeRouteUpdate: Called when the current route is changed but the component is reused. For example, for a path /foo/:id with dynamic parameters, when /foo/2 /foo/1 and 061938f41d0e02, the same Foo component will be rendered, so The component instance will be reused. And this hook will be called in this case. Can access the component instance this
  3. beforeRouteLeave: Called when the navigation leaves the corresponding route of the component, you can access the component instance this

Question: How does vue-router do permission control?

answer:

The most commonly used method of access control for vue-router beforeEach . If you do not have permission, you cannot jump to the route. Generally meta of the routing configuration. When the route is redirected, it will be Trigger the beforeEach global routing guard, and authenticate the authority in this guard to complete the routing authority control. There is another method besides the first time, which is to use the addRoutes method to dynamically vue-router . Before adding the configuration, only the authorized routing information can be registered in the routing.

Q: How many ways are there for vue-router to transfer parameters?

answer:

vue-router There are three ways to transfer parameters:

param

param When configuring routing information, you need to indicate the parameters that need to be received in the routing (such as: url/:id ). Among them, id is param needs to pass. It should be noted that when passing parameters in this form At this time, if no parameters are passed, it cannot be matched to the route correctly. ? before defining the parameter, which means that the parameter is optional, and the corresponding route can be correctly matched regardless of whether the parameter is passed or not. You can add regular after the parameters, such as: url/?:id(\\d+), adding parameters in this form can limit the format of the parameters.

When using param {props:true} configuration item when configuring routing information, then the incoming param props be received in 061938f41d0f63 in the page. In addition to receiving it in this way, you can also use this.$route.params to get it To the parameters. Passing param parameters Whether using router-link or programmatic navigation, if it is the incoming string form, you can directly splice the parameters after the corresponding routing address. If it is in the form of an object, add the params field to the object, and the internal correspondence is the corresponding param parameter.

query

query and param are only slightly different. The query do not need to be defined in the routing configuration. query is optional and will not affect the matching of the routing address. query transmission parameters used query object or later address ? splicing form. When receiving, the passed parameters are obtained this.$route.query

Note: Whether using param or query for routing parameters, when the page is refreshed, the parameters will not be lost, because the parameters are directly stored in the routing address

meta

Personally, it is not recommended to use meta transfer parameters. Although the purpose of parameter transfer can be accomplished through operation, it will cause the loss of parameters when the page is refreshed. However, this kind of parameter transfer is implicit, and the user cannot Learned.

Using meta pass parameters can get the current route object this.$route on the jump page before the route jump, and store the corresponding parameters meta Then use the corresponding method to route the jump. After the jump is completed, use the beforeRouteEnter component hook function on the target page to receive the parameters. Although beforeRouteEnter cannot access this , but in the third parameter, next , a function can be passed in as a parameter, and this parameter can be accessed examples of the current component, after the beforeRouteEnter second parameter form objects can be read into meta data stored in the transmission parameter is completed.

How do you understand Vuex?

answer:

Vuex is Vue . It centrally stores and manages the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner. There are five core attributes:

  1. state: state mainly used to store data and storage state. After registering store in the root instance, use this.$store.state to access the data stored in state The data storage method is responsive. The vue component store . If the data changes, the component will be updated accordingly.
  2. Vuex : The only way to change the state in 061938f41d1147 of store mutation .
  3. action: This method is mutation , the only difference is that the asynchronous method is executed action
  4. Getter: It can be considered as store . Its return value will be cached according to its dependency, and it will be recalculated only when its dependency value changes.
  5. module: store into modules. Each module has state , mutation , action , getter and even nested sub-modules.

When the component performs data modification, we need to call dispatch to trigger the method in actions actions each method in which there will be a commit method, when the method will be executed by commit triggered mutations inside the method to modify the data. mutations each function will have inside a state parameter, so that you can mutations performed inside state data modification, when the data modification is completed, it will be transmitted to the page. The data on the page will also change.

Because the method of passing parameters will be very cumbersome for multi-layer nested components, and the state transfer between sibling components can also be passed through other methods, but it may still feel powerless. We often use parent-child components to directly reference or use events to change and synchronize multiple copies of the state. The above patterns are very fragile and usually lead to unmaintainable code. So we need to extract the shared state of the component and manage it in a global singleton mode. In this mode, our component tree constitutes a huge view, no matter where in the tree, any component can get state or trigger behavior! In addition, by defining and isolating various concepts in state management and enforcing compliance with certain rules, our code will become more structured and easier to maintain.

Low-level interview questions

Vue questions is relatively difficult compared to the above, and may be directly raised by one level. You may need to have enough understanding of 061938f41d1245 related API , and read the relevant source code to understand better.

Q: What are the two cores of Vue?

Answer: They are: data-driven and component systems

Data driven

Vue technical implementation of the 061938f41d12d4 data observation principle uses the ES5 of Object.defineProperty and the memory attributes: getter and setter can be called the observation mechanism based on dependent collection. These getter and setter are not visible to the user internally. Vue can track dependencies property is accessed and modified. The core is VM , that is, ViewModel , which ensures the consistency of data and views. Each instruction may have a target for observation data corresponding to a called watcher , each corresponding to a component instance watcher example, it will render the assembly during the contact data property recorded as dependencies. getter when we collect dependent, dependent on the subscription data is collected change watcher collected dependence collect it when data changes responsive, subscribers can be notified to the respective associated processing logic. setter time will depend update trigger, then when the dependency of setter when triggered, will inform watcher , making it the associated component re-rendering.

Component system

The component system is Vue , because it is an abstraction that allows us to build large applications using small, independent and usually reusable components. Think about it carefully, almost any type of application interface can be abstracted into a component tree. Vue prefers to build a page composed of individual components instead of html . When developing a project, divide the entire application into components to make development easier to manage. And maintenance.

The component system contains several very important parts:

  1. template: The template declares the mapping relationship between the data and the DOM that is finally displayed to the user.
  2. data: The initial data state of a component. For reusable components, this is usually a private state
  3. Props: Pass and share data through parameters between components
  4. methods: Changes to the data are generally carried out in the method of the component
  5. lifecycle hooks: A component will trigger multiple lifecycle hook functions
  6. assets: In Vue.js, user-defined instructions, filters, components, etc. are collectively referred to as resources

Q: How to understand MVVM?

answer:

MVVM mainly composed of three parts: Model , View , ViewModel

  1. Model: Represents the data model, you can also define data modification and business logic in the Model
  2. View: Represents the UI component, which is responsible for transforming the data model into a UI display
  3. ViewModel: represents the object that synchronizes View and Model

In MVVM , View and Model have no direct relationship, and all interact ViewModel ViewModel responsible Model data synchronization to View show, is also responsible for the View modified sync back Model . MVVM essence is to manipulate a view based on the operation data and then operation DOM , by means of MVVM without directly operating DOM , developers only need to complete the view template contains a declaration binding, written ViewModel there business, making View fully automated.

Q: What does Vue initialization do?

answer:

Vue options passed in by the user during initialization, that is, the required parameters, and then create Vue , and define a unique Vue for the instance, which is used to distinguish _uid Vue as Vue Avoid being observed by observers.

After completing the initialization of the instance creation, you need to merge the user options and the system default options. The first thing to deal with is the configuration content of the component. The incoming option is merged with the constructor itself. Here, the pupa strategy is the default configuration and The configuration of the incoming configuration is merged. If it is the instantiation of internal components (subcomponents), and the dynamic options merge will be very slow, and some special parameters options If it is the root component, merging the global configuration options into the configuration of the root component is actually an option merging.

The next step is to initialize the core part. First, initialize the properties related to the life cycle of the Vue root , parent , children , refs , and then initialize the custom component event listener, if there is a parent listener event, add it to the instance On, then initialize the slots, rendering functions, etc. required for render Actually just two things

  1. Slot processing,
  2. $createElm is the declaration of h in the render function

The next step is to execute the beforeCreate hook function, where you can see what initialization a component has done before and after it is created.

After executing the beforeCreate hook function, initialize the injected data, and first inject when passing parameters from generation to generation. As a component, you need to inject the data passed down from the ancestors before providing data to the next-generation components. props , methods , data , computed , watch provide after injecting the data passed down from the ancestors.

Finally, call the created , the initialization is complete, and the mount can be executed, and it is mounted on the element DOM If the component constructor has set the el option, it will be automatically mounted, so there is no need to manually call $mount to mount it.

Q: How to understand Vue's responsive data?

answer:

Vue implements a definedReactive method, internal methods borrowed Object.definedProperty() to each attribute added get/set properties. definedReactive can only monitor the outermost objects, and the inner objects need to recursively hijack data. The array is rewritten seven push , pop , shift , unshift , reverse , sort , splice to intercept data for the array, because these methods will change the original array. The new or deleted attributes of the object cannot be set Only the attribute modification of the object itself will be hijacked. Or use Vue provided by $set() implement monitoring. There is a Dep defineReactive , which is used to collect and render Watcher , and Watcher is used to update the view.

Q: How does Vue perform dependency collection?

answer:

Dep is a class responsible for collecting Watcher , and Watcher is a class that encapsulates the rendering view logic and is used to distribute updates. Note that Watcher is not directly update the view of the need to combine Vnode after patch() in diff algorithm can generate real DOM .

However, each attribute has its own dep attribute to store the dependent Watcher . After the attribute changes, it will notify Watcher to update. Obtaining the user ( getter ) data Vue to each attribute added dep property ( collect as Dependency ) collecting Watcher . When the user setting sets the attribute value, dep.notify() informs the collected Watcher re-render. Dep dependent collection class has a many-to-many bidirectional storage relationship Watcher Each attribute can have multiple Watcher types, because the attribute may be used in different components. At the same time, a Watcher class can also correspond to multiple attributes.

Each attribute can have multiple dependencies. For example, this attribute may be used in computed , watch , and its own data attribute. These dependencies are collected using the response data Dep Watcher is dependent as an intermediary, it can be Dep collection can also be Dep update notification.

Q: How does Vue compile templates?

answer:

Our compiler is written .vue documents in the template label contains html label changes render function, can be understood template template is render package, template in vue source which become transformed into render function:

  1. The template template string is converted into an ast syntax tree (parser parser), where a large number of regularities are used to match the name, attribute, text, etc. of the tag.
  2. The static node static mark for the AST is mainly used to optimize the rendering of the virtual DOM (optimize optimizer). Here, all the child nodes will be traversed and statically marked
  3. Use the AST syntax tree to regenerate the render function code string code.

Q: How does Vue lifecycle hooks implement?

answer:

Vue is just a callback function, and the corresponding hook is called to execute during the process of creating component instantiation. Use Vue.mixin({}) or multiple functions are defined in the life cycle. Vue will call mergeHook() internally to merge the hooks and put them into the queue for execution in sequence.

Q: Vue.mixin usage scenarios and principles?

answer:

Vue.mixin mainly used to extract a common business logic to achieve multiplexing. mergeOptions() is called when executed internally, and the strategy mode is adopted to merge different attributes. If there is a conflict between the mixed data and the data of the component, the component itself is used. Vue.mixin({}) are some defects in 061938f41d199b, which cause naming conflicts between the mixed property name and the component property name, and the source of data dependence.

Question: How does $nextTick work?

answer:

vm.$nextTick(cb) is an asynchronous method that has done a lot of downgrading for compatibility. There are promise.then,MutationObserver , setImmediate , setTimeout . After modifying the data view is not immediately updated, but after set method notify notification Watcher updates will need to update the Watcher put into an asynchronous queue, nexTick callback function to put Watcher behind until the main thread synchronization code Execute the lodging and then clear the queue in turn, so vm.nextTick(callback) is executed after the update of dom

Question: How does vue-router implement?

A: vue-router most commonly used in two modes are hash mode and history mode:

hash mode

hash mode is vue-router . It is marked with a # after the domain name, and window.location.hash the current url is hash . In the hash mode, the hashchange method can be used to monitor the changes of url in hash hash features compatibility mode is better and hash change will be in the browser's history add a record, you can achieve the browser forward and back functions.

history mode

history mode is another mode of the front end of the route, which is based on HTML5 the history object, location.pathname obtain the current routing address url. history mode, by pushState and replaceState may be modified method url address binding popstate listener method url changing routes.

Question: How does vuex work?

answer:

Vuex is initialized, Vue is stored globally. In the install function, it will first determine whether Vue.use(Vuex) has been called, and then call the applyMixin method to initialize some operations. The applyMixin method will only do one thing. $store object on the instance. vuex is used, store mounted on the root component. In the first call vuexInit a function, options.store is the root option store , thus determine its type is not function , if the execution of the function and assigns the result to the root instance $store , otherwise direct assignment.

Vuex the state state is responsive, by means vue of data is responsive, the state into vue component instance data in, Vuex the getters is by vue calculated attribute computed real-time data monitor.

Concluding remarks

The above interview questions are what the interviewers asked during the interview. I did some research, study and sorting out. There may be some mistakes. You can point out the mistakes in the comments below, and you can learn and make progress together. If there are any areas that are not covered, you can also comment and tell me, and fill in later.


Aaron
4k 声望6.1k 粉丝

Easy life, happy elimination of bugs.