preface

Did a dream last night, dreamed that he went to a big factory interview, the interviewer approached the room, sat down: Is Yang Yo? International practice. Let’s introduce ourselves first.

So I began a two-minute self-introduction. Meanwhile, the interviewer listened and looked at my resume, frowning while looking. After that, he asked me: “Vue is often used in your previous projects, are you familiar with it?

I smile at the corners of my mouth, secretly pleased: fortunately, there are special Vue interview questions, it seems that the stability. Hence the answer that installs force again modestly: return line, you literally ask.

So the interviewer see my tone so big, thought: yo ho, to a pack force, labor today only ask Vue.

Original address welcome star

Let’s take a look at Vue’s responsive system

Vue is the MVVM framework. When the data model data changes, the page view will be updated in response. Its principle intercepts the getter/setter method of data (Object.defineProperty or Proxy), and utilizes the publish and subscribe design mode. Subscribe in getter methods, publish notifications in setter methods, and let all subscribers complete the response.

In a responsive system, Vue creates a subscription center for each attribute of the data model data as the publisher, and three roles, namely, watch, computed property, and Template/Render view, serve as subscribers at the same time. For watch, it directly subscrires to observe the attributes of the listener. For computed properties and view-render Template/Render, if an internal execution gets a property of data, it executes a getter for that property, then automatically subscribes to that property, and when the property is modified, it executes a setter for that property, This completes the publication notification of the property, notifying all subscribers of updates.

Difference between computed and Watch

Computed attributes and the watch listener can both observe changes in attributes and respond to them. The difference is:

Computed properties Computed is more of an observer of the cache function. It can perform complex computations of the attributes of one or more data to generate a new value, which the rendering function can use. When dependent attributes change, computed does not immediately recalculate to generate a new value, but marks it as dirty data first. Recalculated and returned only when the next computed object is obtained.

However, the listener Watch is not cacheable. The listener Watch provides a listening function, which will be executed immediately when the listening properties change.

Introduce the Vue lifecycle

BeforeCreate: is the first hook fired after new Vue(), and data and methods on data, methods, computed, and watch cannot be accessed at this stage.

Created: Occurs after the instance is created. The current phase has completed data observation, that is, data can be used and changed. Changing data here does not trigger the updated function. You can do some initial data fetching, you can’t interact with the Dom at this stage, you can access the Dom via vm.$nextTick if you want to.

BeforeMount: Occurs before mounting, before the template template is compiled by importing the rendering function. At this stage, the virtual Dom has been created and is about to start rendering. Data can also be changed at this point without triggering the updated.

Mounted: Occurs after the Dom is mounted. In this mode, data is bidirectional bound. You can access the Dom node and use the $refs attribute to operate the Dom.

BeforeUpdate: Triggered before updates, before reactive data is updated and the virtual DOM is re-rendered, you can make changes to the data at this stage without re-rendering.

Updated: Occurs after the update is complete when the component Dom is updated for the current phase. It is important to avoid changing the data during this period, as this may result in an infinite loop of updates.

BeforeDestroy: Occurs before the instance is destroyed, the instance is fully available in the current phase, at which point we can clean up the aftermath, such as clearing timers.

Destroyed: Occurs after the instance is destroyed, at which point only the DOM shell is left. Components have been disassembled, data bindings removed, listeners removed, and subinstances destroyed.

Why does a component’s data have to be a function

A component may be used in many places, will create a number of instances, if the data is an object, the object is a reference type, a modified the data instance will affect other instances, so data must use function, for each instance to create a their own data, make its different instances of the same components each other.

How do components communicate with each other

  • Parent-child component communication

Parent component -> Child component: prop

Child component -> Parent component: $ON /$emit

Get component instance: use $parent/$children, $refs. XXX to get property data or call component methods

  • Sibling communication

Event Bus: Each Vue instance is an Event Bus, which supports $ON /$EMIT. You can create a new Vue instance between instances of sibling components and communicate with each other as an Event Bus.

Vuex: State and method are extracted to Vuex for sharing

  • Cross-level component communication

Use the dojo.provide/inject

Event Bus: Communicates with its sibling Event Bus

Vuex: State and method are extracted to Vuex for sharing

Here’s how Vue event binding works

Each Vue instance is an Event Bus. When the child component is created, the parent component passes the Event to the child component. When the child component is initialized, the $ON method registers the Event internally. Bind to a real DOM element using addEventListener.

What is slot? What does it do? How does it work?

Slot, also known as slot, is the content distribution mechanism of Vue. The template engine inside the component uses slot elements as an outlet to host the distribution content. Slot is a template tag element of a child component, and whether and how a tag element is displayed is determined by the parent component.

Slots are divided into three categories: default slots, named slots, and scoped slots.

  • Default slot: also known as anonymous search, a default slot to display when slot does not specify a name value, and only one anonymous slot in a component.
  • Named slots: A slot with a specific name, that is, a slot with a name attribute. Multiple named slots can appear in a component.
  • Socket scope: default slot, named slot a variant, can be anonymous slot, can also be named slot, the slot of the difference is in the child component rendering scope slot, could pass data within the child component to the parent component, let father components according to the child components of data passed to decide how to render the slot.

Implementation principle: $slot. Default: vm.$slot.default: vm.$slot. XXX: vm.$slot. In this case, data can be passed to the slot, or if there is data, the slot can be called a scoped slot.

What is the principle behind Vue template rendering?

The template in vue cannot be parsed and rendered by the browser because it is not a standard HTML syntax, so you need to convert the template into a JavaScript function so that the browser can execute this function and render the corresponding HTML element. You can make your view run, and this transformation process is called template compilation.

Template compilation is divided into three stages, parsing parse, optimizing optimize, generating generate, and finally generating render.

  • Parse phase: The Template string is parsed with a large number of regular expressions, converting labels, instructions, attributes, and so on into an abstract syntax tree AST.
  • Optimize phase: Traversing the AST, finding and marking static nodes for diff comparison during page re-rendering, bypassing static nodes and optimizing Runtime performance.
  • Generate phase: Convert the final AST into a render function string.

What is template precompilation?

For Vue components, template compilation is compiled only once, when the component is instantiated, and not after the rendering function is generated. Therefore, compiling is a performance drain on the component runtime.

The purpose of template compilation is simply to convert the template to render function. This process can be completed during the project construction process, so that the actual components can directly skip the template rendering at runtime, thus improving the performance. That’s precompilation.

What’s the difference between template and JSX?

For the Runtime, we just need to ensure that the render function is present, whereas with precompilation we just need to ensure that the render function is generated during the build.

In Webpack, we use vue-loader to compile.vue files. The uE-template-compiler module, which is internally dependent, precompiles the template into the render function during Webpack build.

Like React, after adding JSX’s syntax sugar parser babel-plugin-transform-vue-jsx, you can write the render function directly.

So, template and JSX are both representations of render, except that:

JSX has more flexibility and advantages in complex components than Template, which is a bit of a clunker. Template, however, is much simpler, more intuitive, and more maintainable because of its code structure, which is more consistent with the separation of view and logic.

What is the Virtual DOM

Virtual DOM is an abstract data structure of DOM nodes in JavaScript. The reason why Virtual DOM is needed is that it is expensive to operate DOM in the browser and frequent DOM operation will cause performance problems. The function of the virtual DOM is to compare the virtual DOM before and after the update and find as few real DOM that need to be updated as possible when the page is re-rendered due to the change of responsive data, so as to achieve the purpose of improving performance.

Introduce the Diff algorithm in Vue

When comparing old and new virtual DOM

  • First, compare the node itself to determine whether it is the same node. If not, delete the node to create a new node for replacement
  • If it is the same node, conduct patchVnode to determine how to process the child nodes of the node. First, determine the situation where one party has child nodes and the other does not (if the new children do not have child nodes, remove the old child nodes).
  • Compare if both have child nodes, then perform updateChildren to determine how to operate on the children of these old and new nodes (diff core).
  • When matching, the same child nodes are found and compared recursively

In diFF, only child nodes of the same layer are compared, and cross-level node comparison is abandoned, which makes the time complex and reduces the value O(n) from O(n^3). In other words, only when the old and new children have multiple child nodes, the core diff algorithm is needed to make same-level comparison.

What does the key property do

In the process of diff, a very important condition to judge whether the nodes are the same is whether the keys are equal. If the nodes are the same, the original DOM nodes will be reused as much as possible. So the key attribute is provided for the framework to use during diff, not the developer.

What is the difference between Vue2.0 and Vue3.0

  1. Refactoring the responsive system, replacing Object.defineProperty with Proxy, using Proxy advantages:
  • You can listen directly for changes in array type data
  • The target of listening is the Object itself and there is no need to iterate over every attribute like object.defineProperty, which has some performance benefits
  • 13 methods such as Apply, ownKeys, and HAS can be intercepted, but Object.defineProperty cannot
  • Add/delete object attributes directly
  1. New Composition API for better logic reuse and code organization
  2. Refactoring Virtual DOM
  • Template compile-time optimizations to compile some static nodes into constants
  • Slot optimization, which compiles a slot to a lazy function and gives the decision to render a slot to a child component
  • Extracting and reusing inline events in templates (originally regenerating inline functions for each rendering)
  1. Code structure tweaked to make Tree shaking easier and smaller
  2. Replace Flow with Typescript

Why the Composition API, and what problems does it solve

In Vue2.0, as functionality increases, components become more complex and difficult to maintain, and the root cause of maintenance is that Vue’s API design forces developers to use Watch, computed, and Methods options to organize code instead of actual business logic.

In addition, Vue2.0 lacks a relatively simple and low-cost mechanism to complete logic reuse. Although minxis can complete logic reuse, when the number of mixins increases, it will be difficult to find which mixin the corresponding data, computed or method comes from, making type inference difficult.

Therefore, the emergence of Composition API is mainly to solve the problems caused by Option API. The first one is the problem of code organization. Compostion API allows developers to organize their code according to business logic, so that the code has better readability and extensibility. That is, the next time a developer touches a piece of code that he didn’t write himself, he can better leverage the organization of the code to derive the actual business logic, or better understand the code based on the business logic.

Of course, mixins can also achieve logical extraction and reuse. However, as mentioned above, when multiple mixins function on the same component, it is difficult to see which mixin property comes from. The source is not clear. There is a risk of variable name conflicts in the property of multiple mixins. The Composition API addresses both of these issues.

React Hook and Composition API

From the perspective of React Hook implementation, React Hook determines which useState state comes from the next rendering according to the order of useState calls, so the following restrictions appear

  • You cannot call a Hook in a loop, condition, or nested function
  • Make sure you always call the Hook at the top of your React function
  • UseEffect, useMemo, and other functions must determine dependencies manually

The Composition API is based on Vue’s responsive system implementation, compared to React Hook’s

  • Setup is called once for each component instantiation, whereas React Hook calls the Hook every time it rerenders, making React GC more stressful and slower than Vue
  • The Compositon API calls do not need to be ordered and can also be used in loops, conditions, and nested functions
  • Reactive system automatically realizes dependency collection, and the performance optimization of component parts is completed internally by Vue. However, React Hook needs to manually pass in dependencies and ensure the order of dependencies so that useEffect, useMemo and other functions can correctly capture dependent variables. Otherwise, component performance degrades due to incorrect dependencies.

The Compositon API looks better than React Hook, but the Compositon API is also designed with React Hook in mind.

Did SSR understand? How does it work?

When the client requests the server, the server obtains the relevant data from the database, and renders the Vue components into HTML inside the server, and returns the data and HTML to the client. This process of converting data and components into HTML on the server is called the server side rendering SSR.

After the client gets the HTML and data rendered by the server, the client does not need to request the data again because the data is already there, but only needs to synchronize the data to the component or Vuex. In addition to data, the HTML structure is already available. When rendering components, the client only needs to map THE HTML DOM node to the Virtual DOM, without recreating the DOM node. This process of synchronizing data with HTML is also called client activation.

Benefits of using SSR:

  • Conducive to SEO: In fact, it is beneficial for crawlers to climb your page, because some page crawlers do not support JavaScript execution, and the non-SSR page captured by crawlers that do not support JavaScript execution will be an empty HTML page, and with SSR, these crawlers can obtain complete HTML structure data. Then included in the search engine.

  • Less white screen time: compared to client-side rendering, server-side rendering already gets an HTML text with data after the browser requests the URL, and the browser just parses the HTML and builds the DOM tree. The client rendering needs to get an empty HTML page first, at which time the page has entered a white screen. After that, it needs to load and execute JavaScript, request the back-end server to obtain data, and render the page with JavaScript before the final page can be seen. Especially in complex applications, JavaScript scripts need to be loaded. The more complex the application is, the more and larger the JavaScript scripts need to be loaded. As a result, the first screen of the application takes a long time to load, which reduces the experience.

See thoroughly understand server rendering – SSR principles for more details

The end of the

The interviewer nodded, well, this guy can also, know quite a lot, can get in to write business.

I also secretly pleased, fortunately did not ask me not, and THEN I sat there giggling, smiling and smiling, suddenly heard my alarm bell rang, and then, I woke up.

Then the day began again.

reference

  • “Interview questions” 20+Vue interview questions
  • Interviewer: Talk about your understanding of vue.js framework