1. Concepts of front-end rendering, front-end routing and front-end separation

(1) Back-end routing and back-end routing stage

Back-end rendering: Generate the rendered HTML page directly on the server side and return it to the client side for display

Back-end routing: The server distributes different resource files based on different URLS

Disadvantages: Modules of the entire page are developed and maintained by back-end staff, HTML tags, data and corresponding logic are mixed together and difficult to write and maintain

(2) Separation stage of front and rear ends

With the advent of Ajax, the back end only needed to provide apis to return data, and the front end got the data using Ajax technology and then used javascript to render the data to the page

(3) Front-end rendering and front-end routing

Front-end rendering: The front-end takes the data provided by the back-end and renders the data in javascript

Front-end routing: When the user enters the URL address in the browser, all THE HTML+CSS+JAVASCRIPT resources will be obtained from the static resource server, and then the corresponding resources will be obtained according to different URL addresses. The back-end provides the API to obtain data, and the front-end obtains data through Ajax and renders it to the page using JAVASCRIPT

Vue server render SSR

Concept: The entire HTML fragment rendered by vUE on the client side is done on the server side, and the HTML fragment formed on the server side is returned directly to the client side

Advantages:

  • Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;
  • Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time;

Disadvantages:

  • More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment;
  • More server load: Rendering a full application in Node.js is obviously more CPU-intensive than a server that only serves static files, so if you expect to use it in a high traffic environment, Prepare your server load and use caching strategies wisely.

2. Principle of vue2 and VUe3 response

Vue2: Through data hijacking, publish subscriber model

  1. When variables are first defined in data, a DEP object (dependency: dependency) is created inside VUE. Each variable corresponds to a dependency, in which values are retrieved and set via the defineProperty function inside the object

    Const dep = new dep () //2; const dep = new dep (); DefineProperty (data,key,{//3). Get (){if(dep.target){dep.addSub(dep.target)} return val}, //4. Set (newValue){if(newValue === bal){return}else{val = newValue dep.notify() } } })Copy the code
  2. Publish Subscriber pattern: Defines a DEP class that generates subscriptions for areas of data in data used in a page and adds them to an array of subscribers

    Class Dep(){constroutor(){this.subs = [], constroutor(){this.subs = [], constroutor()} addSub(sub){this.subs.push(sub)} This.subs.foreach (sub=>{sub.upodate()})}}Copy the code

    Principle diagram:

Sample interview answers:

  1. Implements a data listener Observer that listens for all attributes of a data object and notifies subscribers of any changes to the latest values
  2. Implement an instruction listener Compile, scan and parse the instruction of each element node, replace the data according to the instruction template, and bind the corresponding update function
  3. A listener, Watcher, is implemented as a bridge between Observer and Complie, subscribing to and receiving notification of each property change, and executing the corresponding callback function of the directive binding to update the view

In new Vue, data is hijacked in the Observer via Object.defineProperty(). Getter and setter properties for all data are proxy, and Watcher is notified via Dep each time a setter is triggered. Watcher acts as a bridge between the Observer and Complie, notifying Complie to update the view through update when the Observer is listening for data changes. However, Complie subscribes to the corresponding data through Watcher, binds the update function, and adds subscribers through Dep to achieve bidirectional binding.

Vue3:

Through Proxy(Proxy): intercept any operation of any data attributes, including reading and writing of attribute values, adding attributes, deleting attributes, etc..

Reflect: Dynamically performs a specific operation on the corresponding property of the proxied object

Get (target, prop) {return reflect. get(target, prop)}, // Add a new attribute set (target, prop) Prop, value) {return reflect. set(target, prop, value)}, // prop) { return Reflect.deleteProperty(target, prop) } })Copy the code

3. Vue-router Indicates two parameter transmission modes

Router router router router route(the current page of the router)

  1. Path (path:”/index./:id”) is configured in router.js to dynamically pass parameters
  2. Router-link ==>
    This.$route.params

4. Disadvantages and solutions of using V-if and V-for together

Because v-for has a higher priority than V-if, v-IF is executed every time the loop is run. V-if controls the display and hiding of elements by creating and destroying DOM elements, so it will constantly create and destroy elements, which may cause page lag and reduce performance.

Solution: Use V-IF by wrapping an element around or inside the V-for

5. The way of transferring values between VUE components

Parent-child component communication:

  1. prop/$emit

  2. Ref and $parent / $children

    Ref: If used on a normal DOM element, the reference refers to the DOM element; if used on a child component, the reference refers to the component instance

$parent/$children: access parent/ child instances

  1. EventBus($emit / $on)

    An empty VUE instance is used as the central event bus (event hub) to trigger and listen for events

  2. vuex

Intergenerational component communication:

  1. EventBus($emit / $on)

  2. $attr/$listeners

    $attr: contains property bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included, and the internal component can be passed in via v-bind=”$attrs”. Often used in conjunction with the inheritAttrs option.

    $Listeners: Contains V-on event listeners in the parent scope (without.native modifiers). It can be passed into internal components via V-on =”$Listeners”

  3. provide/inject

    The ancestor component provides variables through providers. Variables are then injected into descendant components via Inject. It mainly solves the communication problem between cross-level components, but its application scenario is mainly that the sub-component obtains the state of the superior component, and establishes a relationship between active provision and dependency injection between cross-level components.

  4. vuex

Sibling communication:

  1. EventBus($emit / $on)
  2. vuex

6. How does the parent get the properties and methods of the child

A REF reference is defined on a child component to get its properties and methods in VUE

<templete> <child ref="child"/> </templete> <script> method: {getChild () {this.$refs.child. Property name (method name)}}Copy the code

7. The difference between watch and computed

Computed: Computes attributes, depending on other attribute values, and computed values are cached and recalculated only the next time it gets computed values, if the attribute values it relies on change

Watch: Listener that listens for data and manipulates it through a callback function that triggers a callback when the data changes

Use computed when you need to do numerical calculations and rely on other data, because you can take advantage of the caching nature of computed and avoid recalculating every time you get a value

Watch is used when asynchronous callbacks or expensive operations need to be performed when data changes. Using the Watch option allows us to perform an asynchronous operation (accessing an API), limit how often we perform that operation, and set the intermediate state until we get the final result. These are all things you can’t do with computed properties.

8. What are the main event modifiers in Vue

. Stop: Prevents events from bubbling

.native: bind native events (such as click events for child components)

. Once: The event is executed only once

.self: Binds the event to itself, which prevents the event from bubbling

. Pervent: Prevents default events

.Caption: Used for event capture

9. Your understanding of SPA single page application, its advantages and disadvantages

Concept: SPA(Single-Page Application) loads the appropriate HRTML,CSS, and JAVASCRIPT only when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user’s operation. Instead, IT uses the routing mechanism to transform THE HTML content to avoid the page reload

Advantages:

  1. User experience is good, fast, content changes do not need to reload the entire page, avoiding unnecessary jumps and repeated rendering
  2. Based on the first point, the SPA is less stressful than the server
  3. The front and back ends are separated, and the architecture is clear. The front end carries out interactive logic, and the back end is responsible for data processing

Disadvantages:

  1. The initial loading takes a long time: To achieve the single-page Web application function and display effect, you need to load javascript and CSS uniformly when loading the page, and some of them are loaded on demand
  2. Forward and Backward route management: Because a single page application displays everything on a single page, it cannot use the browser’s forward and backward function, and all page switches need to be managed by its own stack
  3. SEO is difficult: SEO is at a disadvantage because everything is displayed dynamically on one page

10. Difference between V-show and V-if

V-if: true conditional rendering, as it ensures that event listeners and subcomponents within the conditional are properly destroyed and rebuilt during the switch.

V-show: No matter what the initial conditions are, the elements will be rendered, just not displayed

So v-if is suitable for scenarios where conditions rarely change at run time and do not need to be switched frequently, and V-show is suitable for scenarios where conditions need to be switched frequently

11. How to dynamically bind class and style

class:

  1. Object syntax

    <div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>
    data: {
      isActive: true,
      hasError: false
    }
    Copy the code
  2. Array syntax

    <div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
    data: {
      activeClass: 'active',
      errorClass: 'text-danger'
    }
    Copy the code

Style:

  1. Object syntax

    <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
    data: {
      activeColor: 'red',
      fontSize: 30
    }
    Copy the code
  2. Array syntax

    <div v-bind:style="[styleColor, styleSize]"></div>
    data: {
      styleColor: {
         color: 'red'
       },
      styleSize:{
         fontSize:'23px'
      }
    }
    Copy the code

Vue can detect if an array item is assigned a value directly

Due to javascript limitations, Vue cannot detect the following array changes

  1. When an array item is set directly with an index, vm.items[indexOfItem] = newValue
  2. Modify the length of the array, for example:vm.items.length = newLength

To solve the first problem

Vue. Set Vue. Set (vm.items, indexOfItem, newValue) // Vue. $set(vm.items, indexOfItem, newValue) // array.prototype.splice vM. items. Splice (indexOfItem, 1, newValue)Copy the code

To solve the second problem

// Array.prototype.splice
vm.items.splice(newLength)
Copy the code

13. Talk about your understanding of the Vue lifecycle

Concept: A Vue instance has a full life cycle, starting with creating, initializing data, compiling templates, mounting dom -> rendering, updating -> rendering, unloading, etc. We call this the life cycle of a Vue. All functions of VUE are carried out around its life cycle, in different stages of the life cycle corresponding hook functions can achieve component data management and DOM rendering two major functions, there are multiple hook functions in the life cycle, in the process of controlling the whole VUE instance is easier to form a good logic

Functions of each life cycle:

The life cycle describe
beforeCreate When a component instance is created, before its properties take effect
created The component instance is fully created and the properties are bound, but the real DOM is not yet generated and $EL is not yet available
beforeMount Called before the mount begins: The associated render function is called for the first time
mounted El is replaced by the newly created vm.$el, which is called after being mounted to the instance
beforeUpdate Called before component data is updated and occurs before the virtual DOM is patched
update After the component data is updated
activited Keep-alive is exclusive and is called when the component is activated
deactivated Keep-alive is exclusive and is called when a component is destroyed
beforeDestory Called before component destruction
destoryed Called after component destruction

14. Vue parent component lifecycle order

  1. Rendering process:

    Parent beforeCreate() -> Parent created() -> Parent created() -> Parent created() -> Child beforeCreate() -> child created() -> Child created() -> Child created() -> Child created() -> Child created() -> Child created() -> Child created Child component Mounted () -> Parent component mounted()

  2. Parent component update process:

    Parent Component beforeUpdate() -> Parent Component updated()

  3. Sub-component update process:

    Parent Component beforeUpdate() -> Child Component beforeUpdate() -> Child component updated() -> Parent component updated()

  4. Destruction process:

    Parent beforeDestroy() -> child beforeDestroy() -> Child destroyed() -> Parent destroyed()

15. Can a parent component listen to the life cycle of a child component

A parent component can listen for the life cycle of a child component using the @hook: life cycle function name

<template> <child @hook:mounted="getChildMounted" /> </template> <script> method: {getChildMounted () {}Copy the code

16. At what stage can I access the manipulation DOM

Before hook mounted is called, VUE has already mounted the compiled template to the page, so dom can be accessed in Mounted.

VUE life cycle specific adaptation scenarios:

  • BeforeCreate: before creation, this stage is after instance initialization, and this points to the created instance. At this time, the data observation event mechanism has not been formed, and DOM nodes cannot be obtained. Methods and data on data, computed, watch, and methods cannot be accessed. You can add a loading event here.
  • Created: Indicates that an instance has been created, and initialization of imported dependencies for data (data, props, and computed) is complete. Access methods and data on Data Computed Watch Methods. Initialization events are written here, and asynchronous requests are called here as well (not too many requests to avoid a long white screen). You can end the loading event here and do some initialization so that the function executes itself. The DOM is not mounted. If you do DOM operations at this stage, you must put them in the vue.nexttick () callback function.
  • BeforeMount: Before mounting, the root node to which vue is mounted is created, although the specific DOM element is not available. The following vue operations on the DOM continue around this root element. BeforeMount This phase is transitional and is usually used only once or twice for a project.
  • Mounted: creates a vm.$el vm.$el vm. This is where you make a back-end request, get your data back, and do something with the routing hook.
  • BeforeUpdate: Data drives the DOM before data updates. Although the data is not updated immediately after the data is updated, the data in the DOM changes, which is the function of vUE two-way data binding. You can access the existing DOM before updating, for example by manually removing the added event listener.
  • Updated: After data is updated, the virtual DOM is rerendered and patched. The component DOM has been updated to perform dependent DOM operations. Note: Do not manipulate data (modify attributes) in this function; you will get stuck in an infinite loop.
  • Activated: This parameter is sometimes required when vue-router is used<keep-alive></keep-alive>To cache component state so that the Created hook is not called repeatedly. If our child component needs to do something every time it loads, we can use the Activated hook to trigger it.
  • Deactivated:<keep-alive></keep-alive>Used when a component is removed.
  • BeforeDestroy: Make deletion prompts before destroying, such as: Are you sure to delete XX?
  • Destroyed: The current component is deleted and listens for events. The component, event, and subinstance are also destroyed. The component is gone and you can’t manipulate anything inside it.

17. Talk about your understanding of Keep-alive

Keep-alive is a component built into VUE that allows wrapped components to remain in state and avoid re-rendering

Features:

  1. It is used in combination with routing and dynamic components to cache components
  2. Include and exclude, both of which support strings and regular expressions. Include indicates that only components with matching names are cached, and exclude indicates that components with matching names are not cached. Exclude has a higher priority than include
  3. The hook function activated is activated when a component is activated, and the hook function deactivated is activated when a component is removed

Why is data a function in a component

Why must data in a component be a function and return an object when data in a new Vue instance can be an object

// data data() {return {message: "child component ", childName:this.name}} // new Vue new Vue({el: '#app', router, template: '<App/>', components: {App} })Copy the code

If data is an object in a component, then there is no scope isolation. Data properties in subcomponents affect each other. If the data option in a component is a function, then each instance can maintain an independent copy of the returned object. The data property values between component instances do not affect each other. New Vue instances are not reused, so there is no problem referencing objects

19. V – the principle of the model

In the VUE project, v-model instructions are mainly used to create two-way data binding on form input, TextaREA, SELECT and other elements. V-moded internally uses different attributes and throws different events for different input elements

  1. The text and Textarea elements use the value attribute and input event
  2. The checkbox and radio use the Checked property and the change event
  3. The SELECT field takes value as prop and change as an event

Take the input form element for example

<input V-model ='something'> equivalent to <input v-bind:value="something" V-on :input="something = $event.target.value">Copy the code

If in a custom component, the V-Model defaults to using a prop named Value and an event named input

Parent: <ModelChild V-model ="message"></ModelChild> Child: <div>{{value}}</div> props:{value: String}, methods: {test1(){this.$emit('input', 'red ')},},Copy the code

20. Talk about your understanding of Vuex

Definition: VuEX is a state management tool for VUE. At the heart of every Vuex application is the Store. Store is a container that contains most of the states in your application.

Features:

  1. Vuex storage state is responsive. When a Vue component reads state from a store, the corresponding component is updated efficiently if the state in the store changes
  2. The only way to change the state in the store is to show commit mutiation (commit). This allows us to easily track each state change

Module:

  1. State: Data structure that defines the state of the application, where the default initialization state can be set
  2. Getters: Allows the component to get data from the Store. The mapGetters helper function maps the getters in the store to local computed properties
  3. Mutation: The only method that can change the state in a store must be a synchronization function
  4. Actions: Used to process the logic and resubmit mutation when the operation to change state is complex and multiple states are changed
  5. Module: Allows you to split a single store into multiple stores and store them simultaneously in a single state tree

21. Vue-router Routing mode classification

  • Hash: Uses the URL hash value for routing. Support for all browsers, including those that don’t support the HTML5 History Api;
  • History: Relies on the HTML5 History API and server configuration. See the HTML5 History mode;
  • Support all JavaScript runtime environments, such as node.js server side. If the browser API is not found, routing automatically forces the mode into this mode.

22. Implementation principles of hash and History routing modes

  1. Implementation principle of hash mode

    The value of location.hash is what comes after the # in the URL. For example, here is a website whose location.hash value is ‘#search’ : www.word.com*#search*

    Hash mode implementation features:

    1. The hash value in the URL is only a state of the client, that is, when a request is made to the server, the hash part will not be sent.
    2. Changes to the hash value add a record to the browser’s access history. So we can switch the hash through the browser’s back and forward buttons;
    3. You can use the a tag and set the href attribute. When the user clicks on the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash to change the HASH value of the URL.
    4. We can use the HashChange event to listen for changes in the hash value to jump (render) the page.
  2. History mode implementation principle

    HTML5 provides the History API to implement URL changes. History. PushState (), and the history. RepalceState (). Both apis allow you to manipulate the browser’s history without refreshing it. The only difference is that the former is to add a history, the latter is to directly replace the current history

    History mode implementation features:

    1. PushState and repalceState apis to implement URL changes;
    2. We can use the PopState event to listen for URL changes to jump (render) the page;
    3. History.pushstate () or history.replacEstate () will not trigger the popState event, so we need to trigger the page jump (rendering) manually.

23. What is MVVM

Model — View — ViewModel (MVVM) is a software architecture design pattern, an event-driven programming approach that simplifies user interfaces.

View: The View layer is the view layer, which is the user interface. The front end is mostly built with HTML and CSS

Model: The Model layer is the data model, which generally refers to various business logic processing and data manipulation carried out by the back end. For the front end, it is the API interface provided by the back end

View-model: The View-Model layer is the view data layer generated and maintained by the front-end developer organization. In this layer, the front-end developer transforms and encapsulates the Model data from the back end to generate a View data Model that meets the expectations of the View layer.

24. Comparison between Proxy and Object.defineProperty

The Proxy advantage:

  1. The Proxy can listen directly on the entire object rather than on properties
  2. The Proxy can listen for changes to the array directly
  3. Proxy has up to 13 interception methods, not limited to apply, deleteProperty, etc. Object. DefineProperty does not have
  4. The Proxy returns a new object, and we can just manipulate the new object. Object. DefineProperty can only be modified directly by traversing Object attributes
  5. Proxy as a new standard by browser vendors focus on continuous performance optimization

Object. DefineProperty advantage:

It has good compatibility and supports IE9, but Proxy has browser compatibility problems and cannot be smoothed by Polyfill

25. Pros and cons of the virtual DOM

Advantages:

  1. Guaranteed low performance: The framework’s virtual DOM needs to accommodate any operations that the upper-level API might produce, and some of its DOM operations must be implemented in a universal way, so its performance is not optimal. But it’s a lot better than roughing up the DOM directly, so the framework’s virtual DOM can at least guarantee that you don’t need to manually optimize it and still provide good performance, which is the lower limit of performance
  2. No need to manually manipulate the DOM: We don’t need to manually manipulate the DOM, just write the code logic of the View-Model, and the framework will help us update the view in a predictable way based on the two-way binding of the virtual DOM and data, greatly improving development efficiency
  3. Cross-platform: Virtual DOM is a javascript object in nature, and DOM is strongly related to platform. In contrast, virtual DOM can carry out more convenient cross-platform operations, such as server rendering, WEEX development and so on

Disadvantages:

Extreme optimization is not possible: Although virtual DOM + is reasonably optimized to meet the performance requirements of most applications, virtual DOM cannot be optimized specifically in some applications with extremely high performance requirements

26. Implementation principle of virtual DOM

  1. Abstract the real DOM by simulating a real DOM tree with javascript objects
  2. Diff algorithm (Compare the difference between two virtual DOM trees)
  3. Pach algorithm (applying the difference between two virtual DOM objects to a real DOM tree)

27. The role of key in vUE

Key is a unique token for vnodes in Vue. With this key, our diff operation can be more accurate and faster ** “more accurate” : Because there is no local reuse with key, local reuse can be avoided in sameNode function A. key === B. key comparison. So it’s more accurate. “Faster” ** : Use the uniqueness of key to generate map objects to obtain corresponding nodes, faster than traversal

function createKeyToOldIdx (children, beginIdx, endIdx) {
  let i, key
  const map = {}
  for (i = beginIdx; i <= endIdx; ++i) {
    key = children[i].key
    if (isDef(key)) map[key] = i
  }
  return map
}
Copy the code

28. What optimizations have you made for the VUE project

  1. The code level
    1. V-if and V-show are used in different scenarios
    2. Computed and Watch distinguish usage scenarios
    3. V-for traversal must add a key to the item and avoid using v-if at the same time
    4. Long list performance optimization
    5. Destruction of events
    6. Lazy loading of image resources
    7. Third-party plug-ins are introduced on demand
    8. Optimize the infinite list feature
    9. Server rendering SSR, pre-rendering
  2. Webpackc level
    1. Webpack compresses images
    2. Reduce redundant code from ES6 to ES5
    3. Extract common code
    4. Template precompilation
    5. Extract the COMPONENT’s CSS
    6. Optimize SourceMap
    7. Build results output analysis
    8. Compilation optimization of Vue project
  3. Optimization based on Web technology
    1. Enable GIZP compression
    2. Browser cache
    3. The use of CDN

29. What do you know about VUE3

Vue3 supports most of the features of Vue2 and has better typescript support

Vue3 designed a powerful Composition API to replace the Option API in Vue2, which is more reusable

Vue3 uses Proxy and Reflect instead of defineProperty to make data responsive

Vue3 rewrites the implementation of the virtual DOM and tree-shaking

Vue3’s new capabilities are further improved: 41% less package size, 55% faster first render, 133% faster update render, 54% less memory

New reactive apis: REF, Reactive…

New life cycle

New scaffold tool: Vite

New components:

  • Fragment – Document Fragment
  • Teleport – Teleports the location of a component
  • Suspense – Loading interface for loading components asynchronously