The last article only said a question, we did not see the addiction, next we fill curiosity ~~

Want to use Vuejs to break through the 20K necessary hot interview question (ii)-data limit

The v-IF and V-for of the previous article give you a deeper understanding of the overall principle of VUE. Let’s talk about the second question

Why does the Vue component Data have to be a function when the root instance of Vue does not?

SRC \core\instance\ state-js-initdata () SRC \core\instance\ state-js-initdata ()

The function returns a new data object instance each time it executes

The test code is as follows


      
<html>

<head>
    <title>Vue event processing</title>
</head>

<body>
    <div id="demo">
        <h1>Why does the Vue component Data have to be a function?</h1>
        <comp></comp>
        <comp></comp>
    </div>
    <script src=".. /.. /dist/vue.js"></script>
    <script>
        Vue.component('comp', {
            template:'<div @click="counter++">{{counter}}</div>',
            data: {counter: 0}})// Create an instance
        const app = new Vue({
            el: '#demo'});</script>
</body>
</html>
Copy the code

The program doesn’t even pass vUE detection

conclusion

There may be multiple instances of a Vue component. Defining data in object form causes them to share a single data object, and state changes affect all component instances, which is not reasonable; It is defined in the form of a function, which is used as a factory function to return a new data object when initData is used, effectively avoiding the problem of state pollution between multiple instances. This limitation does not exist in the Vue root instance creation process, also because there can only be one root instance and you do not need to worry about this situation.

Want to use Vuejs breakthrough 20K essential hot interview question (3)-key origin

Do you know what keys do and how they work in VUE? Tell me what you think of it.

SRC \core\vdom\ patch.js-updatechildren () SRC \core\vdom\ patch.js-updatechildren ()

The test code is as follows


      
<html>

<head>
    <title>03- The function and principle of key?</title>
</head>

<body>
    <div id="demo">
        <p v-for="item in items" :key="item">{{item}}</p>
    </div>
    <script src=".. /.. /dist/vue.js"></script>
    <script>
        // Create an instance
        const app = new Vue({
            el: '#demo'.data: { items: ['a'.'b'.'c'.'d'.'e'] },
            mounted () {
                setTimeout((a)= > {
                    this.items.splice(2.0.'f')},2000); }});</script>
</body>

</html>
Copy the code

The above example recreates the following process

Do not use the key

If you use key

// First cycle patch A A B C D E A B F C D E // 2nd cycle patch B B C D E F C D E // 3rd cycle patch E C D E F C D E // 4th cycle patch D C D F C D // for the 5th time, patch C C F C // oldCh is finished, and the remaining F in newCh is created and inserted in front of CCopy the code

conclusion

  1. Key is mainly used to update virtual DOM efficiently. The principle is that vUE can accurately judge whether two nodes are the same or not through key during patch, thus avoiding frequent updates of different elements, making the whole patch process more efficient, reducing DOM operations and improving performance.
  2. In addition, not setting a key can cause hidden bugs when the list is updated
  3. Vue also uses the key attribute when transitioning between elements with the same label name. The purpose is to allow VUE to distinguish between them. Otherwise, VUE will only replace its internal attributes without triggering transitions.

Want to use Vuejs to break through 20K necessary hot interview questions (4)- virtual DOM war

What do you think of the diff algorithm in Vue?

  • Lifecycle. Js-mountcomponent ()

    • There may be many keys used in data in a component
  • Patch.js-patchvnode ()

    • PatchVnode is where diff occurs. Overall policy: depth-first, same-layer comparison
  • Patch. Js-updatechildren ()

Test code:


      
<html>

<head>
    <title>Vue source code analysis</title>
    <script src=".. /.. /dist/vue.js"></script>
</head>

<body>
    <div id="demo">
        <h1>Virtual DOM</h1>
        <p>{{foo}}</p>
    </div>
    <script>
        // Create an instance
        const app = new Vue({
            el: '#demo'.data: { foo: 'foo' },
            mounted() {
                setTimeout((a)= > {
                    this.foo = 'fooooo'
                }, 1000); }});</script>
</body>

</html>
Copy the code

conclusion

1. Diff algorithm is an inevitable product of virtual DOM technology: by comparing the old and new virtual DOM (DIFF), the changes are updated on the real DOM; In addition, diff is also required to perform the comparison process efficiently, thus reducing the time complexity to O(n).

2. In vue 2.x, in order to reduce the granularity of Watcher, there is only one Watcher corresponding to each component, and only by introducing diff can we find the changes precisely.

3. When the component instance executes its update function, it compares the last render result oldVnode with the new render result newVnode. This process is called patch.

4. The diFF process follows the strategy of depth-first and same-layer comparison; The comparison between two nodes does different operations based on whether they have child nodes or text nodes; Comparing two groups of child nodes is the focus of the algorithm. First, it is assumed that the head and tail nodes may be the same for four times. If the same node is not found, the search will be performed in a general way, and the remaining nodes will be processed according to the situation after the search. With the help of key, the same node can be found very accurately, so the whole patch process is very efficient.

Want to break through 20K with Vuejs necessary hot interview questions (5)- componentization

What is your understanding of vUE componentization?

Answer the general idea:

The definition of componentization, advantages, usage scenarios and considerations of componentization are described, and some characteristics of componentization in VUE are emphasized.

Source code Analysis 1: Component definitions

// Component definition
Vue.component('comp', {
	template: '<div>this is a component</div>'
})
Copy the code

Component definition, SRC \core\global-api\assets.js

<template>
	<div>
        this is a component
    </div>
</template>
Copy the code

Vue-loader compiles the template as the render function and exports the component configuration object as well.

Source code analysis 2: componentization advantages

lifecycle.js – mountComponent()

Relationships between components, Watcher, render functions, and update functions

Source code analysis 3: componentized implementation

Constructor, SRC \core\global-api\extend.js

SRC \core\vdom\ patch.js-createelm ()

conclusion

  1. Components are independent and reusable units of code organization. Component systems are one of the core features of Vue, enabling developers to build large applications from small, independent, and often reusable components.
  2. Componentized development can greatly improve application development efficiency, testability and reusability.
  3. Components are classified into page components, business components, and general components.
  4. Components of VUE are configuration based. We usually write components that are component configurations rather than components. The framework then generates its constructors, which are based on VueComponent and extend to VUE.
  5. Common componentization technologies in VUE include: attribute Prop, custom event, slot, etc. They are mainly used for component communication and expansion.
  6. Rational division of components helps improve application performance.
  7. Components should be highly cohesive and low coupled;
  8. Follow the principle of one-way data flow.

Want to use Vuejs to break 20K essential hot interview questions (6)- design principles

Talk about the understanding of vUE design principles?

On the vUE website, there are big definitions and features:

  • Progressive JavaScript framework
  • Easy to use, flexible and efficient

So the whole idea of this problem can be elaborated in accordance with this.

Progressive JavaScript frameworks:

Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.

Ease of use

Vue provides core features such as data-responsive, declarative template syntax, and configuration-based component systems. This allows us to focus only on the core business of the application. It is easy to write A VUE application if you can write JS, HTML, and CSS.

flexibility

The biggest advantage of progressive frameworks is their flexibility. If the application is small enough, we may only need vUE core features to complete the functionality. As the application scale grows, libraries and tools such as routing, state management, vuE-CLI, etc., are gradually introduced. Both the application volume and learning difficulty are on an increasing smooth curve.

High efficiency

Super fast virtual DOM and DIff algorithms give our application the best performance.

The quest for efficiency continues, with vue3’s introduction of Proxy responsiveness to data and the compiler’s improvements to static content compilation making VUE even more efficient.

Want to break 20K with Vuejs (7)-MVVM

What is your understanding of MVC, MVP, and MVVM?

We front-end programmers have never used MVC or MVP before. But it just reflects the front-end these years from nothing to have, from have to excellent change process, so along this train of thought answer will be very clear.

“Age

In the web1.0 era, there was no concept of a front end. Most of the development of a web application is written by ASP.NET/Java/PHP, the project is usually composed of multiple aspx/ JSP /PHP files, each file contains HTML, CSS, JavaScript, C#/Java/PHP code, the overall architecture of the system may be like this:

The advantage of this architecture is simplicity and speed, but the disadvantage is also obvious: JSP code is difficult to maintain

In order to make the development more convenient, the code is easier to maintain, and the responsibilities of the front and back end are clearer. MVC development pattern and framework were derived, and the front-end display appeared in the form of templates. Typical frameworks are Spring, Structs and Hibernate. The overall framework is shown in the figure:

With this hierarchical architecture, responsibilities are clear and code is easy to maintain. But the MVC here is limited to the back end, there is some separation between the front and back ends, and the front end only completes the view layer in the back end development.

However, some of the same patterns exist:

  1. Front-end page development efficiency is not high
  2. Unclear responsibilities at the front and back ends

Web 2.0

Since the advent of Gmail, Ajax technology has taken over the world. With Ajax, the responsibilities of the front and back end are much clearer. Because the front end can interact with the back end through Ajax, the overall architecture diagram changes to the following:

Through Ajax and background server data exchange, front-end developers, only need to develop the page this part of the content, data can be provided by the background. Ajax can also partially refresh pages, reducing server load and traffic consumption, and improving user experience. At this time, there began to be full-time front-end engineers. At the same time, the front-end class libraries are slowly developing, the most famous being jQuery.

Of course, there are problems with this architecture: there is no viable development model to accommodate more complex business needs, and the page content is all mixed up, which becomes difficult to maintain once the application scale increases. Hence the MVC of the front end.

Architecture evolution after front and back end separation — MVC, MVP, and MVVM

MVC

The FRONT-END MVC is similar to the back-end, with View, Controller and Model.

Model: Saves application data and synchronizes it with back-end data

Controller: Responsible for the business logic that modifies Model data based on user behavior

View: Responsible for View display and visualization of data in model.

The three form a model like the one shown here:

Such a model, in theory, is feasible. But often in real development, this is not how it works. Because the development process is not flexible. For example, if a small event operation has to go through such a process, then development is no longer convenient.

In a real scenario, we tend to see another pattern, as shown below:

This mode is more flexible in development, backbone.js framework is this mode.

However, this flexibility can lead to serious problems:

  1. Data flow is chaotic. The diagram below:

  1. View is big and Controller is thin: Because many developers write logic code in View, gradually the content in View gets bigger and the Controller gets thinner and thinner.

Where there are defects, there will be changes. The reason the MVP model seems to be missing from the front end is that AngularJS brought the MVVM framework model to the front end early. The MVP model, while not very common in front end development, is still considered in native android development.

MVP

MVP is close to MVC. The P stands for Presenter, a middleman who is responsible for the flow of data between the View and the Model and prevents the View from communicating directly with the Model. We can look at the diagram

As you can see, the Presenter is responsible for bidirectional interaction with the Model and bidirectional interaction with the View. This interaction is a little less flexible than MVC, the VIew becomes a passive VIew, and it becomes small. Although it separates the View from the Model. But as applications get bigger, they become larger and harder to maintain. The answer to this problem may be found in the thinking of MVVM.

MVVM

First, what is MVVM? MVVM can be decomposed into (model-view-viewModel). ViewModel can be thought of as an advanced version of presenter. As shown in the figure:

ViewModel automatically responds to data changes in Model by implementing a set of data response mechanism;

And the Viewmodel implements an update strategy that automatically translates data changes into view updates;

Modify the data in the Model in response to user interaction in the View through event listening.

This saves a lot of DOM manipulation code in the ViewModel.

MVVM keeps the View and Model loosely coupled while reducing the amount of code that maintains their relationship, allowing users to focus on business logic while balancing development efficiency and maintainability.

conclusion

  • All three are framework patterns designed to solve the problem of coupling Model and View.

  • MVC pattern appeared earlier and was mainly applied in the back end, such as Spring MVC, ASP.NET MVC, etc. It was also applied in the early front-end field, such as backbone.js. Its advantages are clear layering, while its disadvantages are data flow chaos and maintenance problems caused by flexibility.

  • MVP mode is an evolutionary form of MVC. Presenter, as the middle layer, is responsible for MV communication, which solves the coupling problem between the two. However, the bloated P layer will lead to maintenance problems.

  • MVVM mode is widely used in the front-end field. It not only solves the MV coupling problem, but also solves the maintenance of a large number of complex codes and DOM operation codes. It improves the development efficiency and readability while maintaining superior performance.

Want to break 20K with Vuejs (8)- Performance optimization

What do you know about Vue performance optimization?

The optimization of Vue code level is discussed here

  • Route lazy loading

    const router = new VueRouter({
      routes: [{path: '/foo'.component: (a)= > import('./Foo.vue')}]})Copy the code
  • Keep-alive cache page

    <template>
      <div id="app">
        <keep-alive>
          <router-view/>
        </keep-alive>
      </div>
    </template>
    Copy the code
  • Reuse DOM using V-show

    <template> <div class="cell"> <! <div v-show="value" class="on"> <Heavy :n="10000"/> </div> <section v-show="! value" class="off"> <Heavy :n="10000"/> </section> </div> </template>Copy the code
  • V-for traversal avoids using v-if simultaneously

    <template>
        <ul>
          <li
            v-for="user in activeUsers"
            :key="user.id">
            {{ user.name }}
          </li>
        </ul>
    </template>
    <script>
    	export default {
            computed: {
              activeUsers: function () {
                return this.users.filter(function (user) {
                 return user.isActive
                })
              }
            }
        }
    </script>
    
    Copy the code
  • Long list performance optimization

    • If the list is purely a data presentation and nothing changes, there is no need to be reactive

      export default {
        data: (a)= > ({
          users: []}),async created() {
          const users = await axios.get("/api/users");
          this.users = Object.freeze(users); }};Copy the code
    • If it is a long list of big data, virtual scrolling can be used to render only a few areas of content

      <recycle-scroller
        class="items"
        :items="items"
        :item-size="24"
      >
        <template v-slot="{ item }">
          <FetchItemView
            :item="item"
            @vote="voteItem(item)"
          />
        </template>
      </recycle-scroller>
      
      Copy the code

      See vue-virtual-scroller and vue-virtual-scroll list

  • Destruction of events

    When a Vue component is destroyed, all its instructions and event listeners are automatically unbound, but only for the component’s own events.

    created() {
      this.timer = setInterval(this.refresh, 2000)
    },
    beforeDestroy() {
      clearInterval(this.timer)
    }
    
    Copy the code
  • Lazy loading of images

    For pages with too many pictures, in order to accelerate the page loading speed, we often need to not load the pictures that do not appear in the visual area of the page, and then load them after scrolling to the visual area.

    <img v-lazy="/static/img/1.png">
    
    Copy the code

    Reference project: VUe-Lazyload

  • Third-party plug-ins are introduced on demand

    Third-party component libraries such as Element-UI can be introduced on demand to avoid being too bulky.

    import Vue from 'vue';
    import { Button, Select } from 'element-ui';
    
     Vue.use(Button)
     Vue.use(Select)
    
    Copy the code
  • Stateless components are marked as functional components

    <template functional>
      <div class="cell">
        <div v-if="props.value" class="on"></div>
        <section v-else class="off"></section>
      </div>
    </template>
    
    <script>
    export default {
      props: ['value']
    }
    </script>
    
    Copy the code
  • Subcomponent segmentation

    <template> <div> <ChildComp/> </div> </template> <script> export default { components: { ChildComp: { methods: {heavy () {/ * time-consuming task * /}}, render (h) {return h (' div ', this heavy ())}}}} < / script >Copy the code
  • Localization of variables

    <template>
      <div :style="{ opacity: start / 300 }">
        {{ result }}
      </div>
    </template>
    
    <script>
    import { heavy } from '@/utils'
    
    export default {
      props: ['start'],
      computed: {
        base () { return 42 },
        result () {
          const base = this.base // 不要频繁引用this.base
          let result = this.start
          for (let i = 0; i < 1000; i++) {
            result += heavy(base)
          }
          return result
        }
      }
    }
    </script>
    
    Copy the code
  • SSR

Want to break 20K with Vuejs (9)-Vue3.0

Have you heard about the new features of Vue3.0?

According to the PPT summary of UVU, the main improvements of Vue3.0 are as follows:

  • faster
    • Virtual DOM rewriting
    • Optimization of slots generation
    • Static tree lifting
    • Static attribute promotion
    • Reactive system based on Proxy
  • Smaller: Optimize core library size by tree shaking
  • Easier to maintain: TypeScript + modularity
  • More friendly
    • Cross-platform: Compiler core and runtime core are platform independent, making Vue easier to use with any platform (Web, Android, iOS)
  • Easier to use
    • Improved TypeScript support, with editors that provide robust type checking and errors and warnings
    • Better debugging support
    • Independent responsive module
    • Composition API

Virtual DOM rewriting

Expect more compile-time hints to reduce runtime overhead and more efficient code to create virtual nodes.

Component quick path + single call + child node type detection

  • Skip unnecessary conditional branches
  • JS engines are easier to optimize

Optimized slots generation

Parent and child levels can be individually rerendered in VUe3

  • Ensure that the instance tracks dependencies correctly
  • Avoid unnecessary parent/child component rerendering

In Static Tree ascending case, apply as follows:

Using static tree promotion means that Vue 3’s compiler will be able to detect what is static and then promote it, reducing the cost of rendering.

  • Skip patching the entire tree to reduce rendering costs
  • It works even if it appears multiple times

Static attribute promotion With static attribute promotion, Vue 3 patches skip nodes whose attributes do not change.

Proxy-based data responsiveness

Vue 2’s reactive system uses getters and setters for Object.defineProperty. Vue 3 will use ES2015 Proxy as its observation mechanism, which will bring the following changes:

  • Component instance initialization speed increased by 100%
  • Using Proxy saves half the memory overhead and speeds up speed, but there are incompatibations with lower browser versions
  • To continue support for IE11, Vue 3 will release a build that supports both the old observer mechanism and the new Proxy version

High maintainability

Vue 3 will bring more maintainable source code. Not only does it use TypeScript, but many packages are decoupled and more modular.

Summary statement

Students, read the above interview answers, I don’t know if you have any gains. Village chief here is more wordy two sentences, we must not only recite answers, but also learn to answer ideas and learning methods, so that no matter what problems we encounter in the future, we can do.

Generally speaking, enhancing internal force is the most important goal, no matter what language and frame you use in the future, you will easily control, easy to use.

Previous recommendations:

Want to break 20K with Vuejs (1) V-if

Use Vue +node to build a front-end anomaly monitoring system

Move a small hand to point a praise, and xiaobian together brave front circle, welcome to leave a comment, discuss yo ~~