Summary of front-end interview questions (theory part two) --vue

 What are the advantages of Vue?

1) Lightweight framework: only focus on the view layer, which is a collection of views for building data.

2) Two-way data binding makes data manipulation easier

3) Componentization: realize html encapsulation and reuse

4) Separation of views, data, and structures: making data changes easier, without modifying logic codes, just manipulating data

5) Virtual DOM: DOM operation consumes more performance, do not use native DOM operation nodes

ps:vue is not conducive to SEO

The difference between watch and computed in Vue

1. Computed is a computed attribute; watch is a monitor that monitors data changes in data.
2. Computed supports caching. When the value of the attribute it depends on changes, the computed attribute will be recalculated. Otherwise, the attribute value in the cache will be used; watch does not support caching. When the corresponding attribute changes, the response will be executed.
3. Computed does not support asynchronous operation, and cannot monitor data changes when there is asynchronous operation; watch supports asynchronous operation.
4. Computed will listen when it is loaded for the first time; watch will not listen when it is loaded for the first time by default.

    immediate Whether to execute when the component is created
    immediate: true, listen when it is loaded for the first time (default is false)
    deep deep monitoring is not recommended (very consuming performance)
    if the monitored attribute is an object, if you do not enable deep object sub-attribute changes will not trigger Watch
    is turned on and all sub-attribute changes inside the deep object will trigger watch
5. Functions in computed must call return; watch is not.
6. Usage scenarios:
computed: one attribute is affected by multiple attributes, such as: shopping cart product settlement.
watch: One piece of data affects multiple pieces of data, such as: search data.
In response to data changes, performing asynchronous operations, or high-performance consumption operations, watch is the best choice.

Array usage of bound class

  • object method v-bind:class="{'orange': isRipe, 'green': isNotRipe}"
  • Array method V-bind: class="[class1, class2]"
  • 行内 v-bind:style="{color: color, fontSize: fontSize+'px'}"

What are the commonly used instructions in development

v-show v-if  v-html v-text v-model  v-on v-clock  v-bind

What are the modifiers

event modifier

  • .stop prevents the event from continuing to propagate
  • .prevent prevents label default behavior
  • .capture uses the event capture mode, that is, the event triggered by the element itself is processed here first, and then handed over to the internal element for processing
  • .self triggers the handler only when event.target is the current element itself
  • The .once event will only fire once
  • .passive tells the browser that you don't want to prevent the event's default behavior

Modifiers for v-model

  • .lazy is converted to resynchronization on the change event through this modifier
  • .number automatically converts the user's input value into a numeric type
  • .trim Automatically filter the leading and trailing spaces entered by the user

There are three main types of vue slots:

Default slots, named slots, and scoped
slots The slots in vue refer to a placeholder provided in the child component for the parent component;
indicated by the label, the parent component can fill any placeholder in this placeholder Template code, such as HTML, components, etc., the filled content will replace the tags of sub-components (replace placeholders).

The principle of v-model

In the vue project, the v-model instruction is mainly used to create two-way data binding on form input, textarea, select and other elements. We know that v-model is essentially just syntactic sugar, and v-model uses different input elements internally. properties and throw different events:

text and textarea elements use value attributes and input events;

checkbox and radio use checked attribute and change event;

select field takes value as prop and change as event;

Take the input form element as an example:

<input v-model='something'>

equivalent to

<input v-bind:value="something" v-on:input= "something =Sevent.target.value">

If in a custom component, v-model will by default utilize a prop named value and an event named input, as follows:

父组件:
<ModelChild v-model="message"></ModelChild>子组件:
<div>{
   
   {value}}</div>props:value:String
},
methods:{test1(){this.$emit('input','小红')},
},

Vue's life cycle

The process from Vue instance creation to destruction is called life cycle. A series of processes from the beginning of creation, initialization of data, compilation of templates, mounting of DOM->rendering->update->rendering, unloading, etc. is called the life cycle of vue.

Relevant knowledge points:

1) The vue life cycle has a total of 8 stages: before and after creation, before and after loading, before and after updating, and before and after destruction

2) The first trigger will trigger several hooks: beforeCreate created beforeMount mounted

3) In which life cycle DOM rendering has been completed: mounted

4) The execution order of parent-child component hooks in vue:

father beforeCreate-> father created-> father beforeMount-> child beforeCreate-> child created-> child beforeMount-> child mounted-> father mounted

Update: father beforeUpdate-> child beforeUpdate-> child updated-> father updated

Destroy: parent beforeDestory->child beforeDestory->child destroyed->parent destroyed

The role of the vue life cycle

Form a good logic in the process of controlling the entire vue instance. (Multiple event hooks in the lifecycle)

Communication between vue components

1) vuex

2)eventBus

3)props/emit

4)$parent/$children

5)$attrs/$listeners

The principle of two-way binding data

Vue's two-way data binding is implemented through data hijacking combined with the publisher-subscriber model. Hijack the getter/setter of each property through Object.defineProperty(). The modification triggers the assignment of the method set method, the acquisition triggers the value of the get method, sends a message to the subscriber when the data changes, triggers the corresponding callback and publishes the message through data hijacking

Responsive means that once the data of the component changes, it will immediately trigger the update of the view. He is the first step towards a data-driven view.

A core API of vue responsiveness is Object.defineProperty(). Using Object.defineProperty to rewrite get and set, and turning the assignment and acquisition of object properties into functions, we can implement a simple two-way binding.

Explain one-way data flow and two-way data binding

Unidirectional Data Flow: As the name suggests, data flow is unidirectional. The direction of data flow can be tracked, and the flow is single, which makes it faster to track down problems. The disadvantage is that it is not convenient to write. To make the UI change, you must create various  action to maintain the corresponding  state.

Two-way data binding: The data is connected, and the operation of changing the data is hidden inside the framework. The advantage is that it simplifies a lot of code that has nothing to do with business in scenarios where there are many form interactions. The disadvantage is that it is impossible to track changes in local states, which increases the difficulty of debugging when errors occur.

Why data in vue component must be a function 

Because of the characteristics of JS itself, if data is an object, then since the object itself is a reference type, when we change one of the properties, it will affect the data of the vue instance. If data returns an object as a function, the data of each instance is independent and will not affect each other.

Real DOM and Virtual DOM

 If there are 10 actions to update the DOM in one operation, when you use the traditional source api or jQuery to operate the DOM, the browser will start to build the DOM tree and execute the process from beginning to end; but the virtual DOM will not operate the DOM
 immediately , but save the diff content of these 10 updates in a local js object, and finally attach this js object to the DOM tree at one time, notify the browser to perform the drawing work, and then perform subsequent operations to avoid a lot of unnecessary Calculations.

The role of key in Vue

The role of the key value in vue can be considered in two cases:

  • The first case is using key in v-if. Since Vue renders elements as efficiently as possible, it is common to reuse existing elements rather than rendering them from scratch. Therefore, when using v-if to implement element switching, if there are elements of the same type before and after the switch, then this element will be reused. If it is the same input element, the user's input will not be cleared before and after switching, which does not meet the requirements. Therefore, an element can be uniquely identified by using a key. In this case, the element using the key will not be reused. At this time, the function of key is to identify an independent element.
  • The second case is using key in v-for. When using v-for to update the list of rendered elements, it uses the "in-place reuse" strategy by default. If the order of the data items changes, Vue will not move the DOM elements to match the order of the data items, but simply reuse each element here. Therefore, by providing a key value for each list item, Vue can track the identity of the element, so as to achieve efficient reuse. At this time, the function of the key is to efficiently update and render the virtual DOM.

key is the unique mark of vnode in Vue, through this key, the diff operation can be more accurate and faster

  • More accurate: because it is not in-place multiplexing with key, in-place multiplexing can be avoided in the sameNode function a.key === b.key comparison. So it will be more accurate.
  • Faster: Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method

Why does v-for need to add key

Without keys, Vue uses an algorithm that minimizes dynamic elements and tries to modify/reuse elements of the same type in-place as much as possible. key is the unique mark of vnode in Vue, through this key, our diff operation can be more accurate and faster

More accurate : because it is not in-place multiplexing with key, in-place multiplexing can be avoided in the sameNode function a.key === b.key comparison. So it will be more accurate.

Faster : Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method

hash and history

1. Vue-router (front-end routing) has two modes, hash mode and history mode
1). Hash refers to the # sign behind the url and the following characters. History does not have #, which looks better than hash mode
2). The difference in principle (principle)
3). hash can be compatible to IE8, and history can only be compatible to IE10
; Change the url fragment after #); although the hash path appears in the URL, it will not appear in the HTTP request, and has no effect on the backend at all, so changing the hash value will not reload the page, basically using hash to implement the frontend routed.

2. Principle:
1) .hash finds the corresponding routing rules by listening to the browser's onhashchange() event change

2). History principle: Use two new APIs pushState() and replaceState() in H5's history and an event onpopstate to monitor URL changes

   The history mode URL must be consistent with the backend, so changing to history also requires the cooperation of the backend, otherwise an error will be reported.
So the hash mode is to directly change the thing after "#" every time the page is refreshed. Every time the history is refreshed, it will re-request the entire URL from the backend, that is, re-request the server. If the backend does not respond in time, an error 404 will be reported! . The advantage of history is that the history can be modified, and it will not initiate a request to the backend immediately. However, if there is no hard standard requirement for the project, we can directly use the hash mode to develop.

(1) Implementation principle of hash mode The
early implementation of front-end routing is based on location.hash. The realization principle is very simple, the value of location.hash is the content after # in the URL. For example, the following website, its location.hash value is '#search':
https://www.word.com#search
The implementation of hash routing mode is mainly based on the following characteristics:

  • The hash value in the URL is only a state of the client, that is to say, when a request is made to the server, the hash part will not be sent;
  • A change in the hash value will add a record to the browser's access history. Therefore, we can control hash switching through the back and forward buttons of the browser;
  • You can pass the a tag and set the href attribute. When the user clicks on this tag, the hash value of the URL will change; or use JavaScript to assign a value to loaction.hash to change the hash value of the URL;
  • We can use the hashchange event to monitor changes in the hash value, thereby jumping (rendering) the page.

(2) Implementation principle of history mode HTML5 provides History API to realize URL changes. Among them, there are two main APIs: history.pushState() and history.repalceState(). These two APIs can manipulate the browser's history without refreshing it. **The only difference is that the former is to add a new historical record, while the latter is to directly replace the current historical record, as shown below: ** window.history.pushState(null, null, path); window.history.replaceState( null, null, path);

  • The implementation of the history routing mode is mainly based on the following characteristics:
  • PushState and repalceState two APIs to operate and implement URL changes;
  • We can use the popstate event to monitor the change of the url, so as to jump (render) the page;
  • history.pushState() or history.replaceState() will not trigger the popstate event, then we need to manually trigger the page jump (rendering).

Vue initialization page flashing problem

When using vue to develop, before vue is initialized, since div is not under the control of vue, the code we write will be prone to blurry phenomenon before parsing, and we will see words similar to {{message}}, although Under normal circumstances, this time is very short, but it is still necessary to let this problem be solved.

First: add the following code in css: v-cloak] { display: none;}

If it doesn't completely solve the problem, add to the root elementstyle="display: none;" :style="{display: 'block'}

How does Vue dynamically increase object properties

1.this.$set(this.obj,key,value)

2.this.obj=Object.assign({},this.obj,{a:1,b:2});

Life cycle of routing guards

1. The life cycle of the global routing guard:

(1) router.beforeEach((to,from,next)=>{  })

Time to take effect: when navigation is triggered

(2) router.beforeResolve((to,from,next)=>{  })

Effective timing: before the navigation is confirmed, and after the guards and asynchronous routing components in all components are resolved

(3)router.afterEach((to,from)=>{  })

2. The life cycle of local routing guards:

(1)beforRouteEnter(to,from,next){  }

Note: Called before the route corresponding to the rendered component is loaded into the interface, you cannot use 'this' to get the component instance, because the component instance has not been created before the guard is executed

(2)beforeRouteUpdate(to,from,next){ }

Note: Called when the current route changes, you can use 'this' to access the component instance

(3)beforeRouterLeave(to,from,next){  }

Note: Called when navigating away from the route corresponding to the component, you can use 'this' to access the component instance

The difference between route and router

route is used to obtain routing information, and router is used to operate routing.

Vue-Router

vue-router is the official routing manager of Vue.js. It is deeply integrated with the core of Vue.js, making it easy to build single-page applications. Included features are:

  • nested routes
  • Modular, component-based routing configuration
  • Route parameters, queries, wildcards
  • View transition effect based on Vue.js transition system
  • Fine-grained navigation control
  • Links with auto-activated CSS classes
  • History mode or hash mode, automatically downgraded in IE9
  • custom scrollbar behavior

vue-router component:

  • < router-link to=""> route path
  • < router-link :to="{name:''lrouting name'}"> named route
  • < router-view> display of routes

What kinds of navigation hooks does vue-router have?

1. Global navigation hook

    1) Front hook:

router.beforeEach((to, from, next) => {  })

    2) Rear hook

router.afterEach((to,from) => {  })

2. Separate routing exclusive hook

{
    path: '/home',
    name: 'home',
    component: Home,
    beforeEnter(to, from, next) {
        if (window.localStorage.getItem("id")) {
            next()
        } else {
            next({ name: "login" })
        }
    }
}

3. Hooks inside components

beforeRouteEnter(to, from, next) {
    // do someting
    // 在渲染该组件的对应路由被 confirm 前调用
},
beforeRouteUpdate(to, from, next) {
    // do someting
    // 在当前路由改变,但是依然渲染该组件是调用
},
beforeRouteLeave(to, from ,next) {
    // do someting
    // 导航离开该组件的对应路由时被调用
}

Global Parsing Guard

router.beforeResolve registers a global guard, similar to router.beforeEach

Advantages of Vite packaging

1) Fast cold start

2) Package compilation speed

3) Hot module update

Talk about VUEX

  • state: the place to put the state, the basic data of vuex, used to store variables
  • Mutation: The method of submitting updated data, synchronous
  • getter: Data derived from the basic data state, which is equivalent to the computed property of the state
  • action: The function is roughly the same as Mutation, the difference is that action submits mutation instead of directly changing the state. action can contain any asynchronous operation.
  • modules: Modular VUEX, each module can have its own state mutation action getter

The difference between Vue2 and Vue3

1. Refactoring of responsive system, use proxy to replace Object.defineProperty attribute, advantages:

    - Proxy can directly monitor the `add/delete` property of the object;

    - Proxy directly monitors the changes of the array

    - The target of Proxy monitoring is the object itself. It does not need to traverse each property like Object.defineProperty, which has a certain performance improvement

2. Add `Composition API` (Composition API), better logic reuse and code organization:

    - setup configuration

    - ref and reactive

    - watch与watchEffect

    -provide and inject

3. Reconstruct virtual DOM, diff algorithm

4. Life cycle renaming

    - beforeDestroy was renamed to beforeUnmount

    - destroyed is renamed to unmounted

// Vue3.0 also provides a lifecycle hook in the form of Composition API, which corresponds to the hook in Vue2.x as follows:

vue3:onBeforeMounted=>onMounted=>onBeforeUpdate=>onUpdated=>onBeforeUnmount

beforeCreate ===> setup()

created      ===> setup()

beforeMount  ===> onBeforeMount

mounted      ===> onMounted

beforeUpdate ===> onBeforeUpdate

updated      ===> onUpdated

beforeUnmount===> onBeforeUnmount

unmounted    ===> onUnmounted

4. New built-in components:

    - Fragment

    - Teleport

    - Suspense

5. Removed parts:

    - Removed v-on.keyCode modifier, also no longer support config.keyCodes

    - remove v-on.native modifier,

    - remove filter

    - It is `deprecated` to use mixins anymore, composition functions are better mixin replacements by themselves

6. Definition of data and methods

vue2: data() { return {}; }, methods:{ }

vue3 : data and methods are defined in the setup, and unified

return{}

watch和watcheffect

What is the difference between computed properties and event methods

We can define the same function as a  method or a computed property. For the end result, both ways are the same.

difference:

  • computed: Computed properties are cached based on their dependencies and are only re-evaluated when their related dependencies change.

  • methodmethod : The call will always execute this function whenever a re-render occurs  .

Manage multiple page data module decoupling (vuex)

What is the core of Vue

Data-driven, component system.

The function and principle of $nextTick() in Vue

Vue is executed asynchronously when updating the Dom. After modifying the data, the view will not be updated immediately, but after all the changes in the loop are completed at the same time, the view will be updated uniformly. So after we modify the data, we immediately get the DOM in the method, and what we get is still the unmodified DOM.

$nextTick is a delayed callback after the next DOM update cycle ends. Automatically execute after DOM update

function inside.

Function of $nextTick: The code in this method will be executed after the rendering is completed, which solves the problem that the latest DOM cannot be obtained by asynchronous rendering

Application scenario: In the hook function created(), if you want to obtain and manipulate DOM, put the method of manipulating DOM in $nextTick

MVC explained

The full name of MVC is Model View Controller, which is the abbreviation of model (model)-view (view)-controller (controller). The business logic is gathered into one component, while improving and customizing the interface and user interaction, there is no need to rewrite the business logic. MVC was uniquely developed to map traditional input, processing, and output functions in a logical GUI structure.

Almost all Apps only do one thing: display data to users and handle user operations on the interface.
The idea of ​​MVC: One sentence description is that the Controller is responsible for displaying the data of the Model with the View, in other words, assigning the data of the Model to the View in the Controller.

MVVM

MVVM:Model、View、ViewModel。

You will subconsciously compare it with MVC, and you will find that MVVM has one more ViewModel and less Controller.

First, let’s talk about the extra ViewModel (VM, not video memory).
The meaning of VM, like Model, lies in data.
Model is responsible for fetching and storing data. However, in addition to fetching and storing data, we also have a very important operation: parsing.
 

MVVM pattern

The core idea of ​​MVVM is to pay attention to the changes of the model, and let the MVVM framework use its own mechanism to automatically update the DOM, which is the so-called data-view separation, and the data will not affect the view. (view{page}-model{data}-modelview{conversion processing between bridge view and data})

1) MVVM realizes the two-way binding of data and pages

2) MVVM realizes the decoupling between page business logic and rendering, as well as data and view decoupling, and can be developed in components.

3) How does VUE embody the idea of ​​MVVM: Mustache syntax realizes the binding of data and views; v-on event binding, when data is manipulated through events, v-model will change accordingly.

MVC explained

 The full name of MVC is Model View Controller, which is the abbreviation of model (model)-view (view)-controller (controller). The business logic is gathered into one component, while improving and customizing the interface and user interaction, there is no need to rewrite the business logic. MVC was uniquely developed to map traditional input, processing, and output functions in a logical GUI structure.

Almost all Apps only do one thing: display data to users and handle user operations on the interface.
The idea of ​​MVC: One sentence description is that the Controller is responsible for displaying the data of the Model with the View, in other words, assigning the data of the Model to the View in the Controller.

MVVM

What is MVVM
MVVM: Model, View, ViewModel.

You will subconsciously compare it with MVC, and you will find that MVVM has one more ViewModel and less Controller.

First, let’s talk about the extra ViewModel (VM, not video memory).
The meaning of VM, like Model, lies in data.
Model is responsible for fetching and storing data. However, in addition to fetching and storing data, we also have a very important operation: parsing.
 

Guess you like

Origin blog.csdn.net/Holly31/article/details/130740881