15 advanced interview questions of vue.js

Time:2019-12-7

Crazy technology house

https://www.zeolearn.com/inte…

No reprint without permission

1. When rendering the item list, what is the function and importance of the key attribute?

When you render a list of projects,keyProperty allows Vue to track each vnode. The key value must be unique.

If the key attribute is not used, and the contents of the list have changed (for example, sorting the list), the virtual DOM would rather use the updated data to patch the nodes to reflect the changes, rather than move the elements up and down. This is the default mode, which is very effective.

When a unique key value is provided, the elements are reordered according to the changes to the key (and they are not patched with new data). If the key is deleted (for example, when items in the list are deleted), the corresponding element node is also destroyed or deleted.

Please note the following figure:

15 advanced interview questions of vue.js

Here is a parent component rendering a list of child components. We see that three list items are rendered as three subcomponent nodes. Each of these subcomponents contains a span tag and an input box, and possibly a local state object. Now let’s examine two situations:

When the key attribute is not used: for example, if the list has been reordered, Vue will use the reordered data to simply patch the three existing nodes without moving them. This method works as long as the user does not enter or change the local state of one or more of these subcomponents. Therefore, suppose that the user has entered the input box with component number 3. After reordering the list, the content of the span tag with component number 3 will be changed, but the input box will remain here together with the status data of the user’s typing. This is because Vue doesn’t recognize component number 3, it just refines the update data it sees, the contents of the span tag.

When the key attribute is used on a subcomponent, Vue knows the identity of the component, and when reordering the list, it moves the node instead of patching it. This ensures that manually edited input boxes and the entire component move to the new location.

When conditionally rendering a component or element, you can also use the key attribute to signal Vue about the uniqueness of the element and ensure that the element is not patched by new data.

2. How will you render the original HTML in the template?

A typical way to output content in a template is to use the mustache syntax tag to output data from a method, property, or data variable. But the mustache tag renders the text. If you try to render HTML using the mustache tag, it will render as a text string and will not be parsed. To render and parse content into HTML, we can use the v-html directive, as shown below.

Template

<div id="app" v-html=”title”></div>

App

new Vue({
    el: '#app',
    data: {
      title: '<h1 style="color: green;">Vue.js</h1>'
    }
});

output

Vue.js

As shown in the above example, the v-html instruction parses all HTML, and the above statement will render as needed. Developers must understand v-html in the premise of using. If v-html is used improperly, the website may suffer from injection attack, and it is likely to inject and execute malicious code from external sources.

3. What is Vue loader?

Vue loader is the loader module of webpack, which enables us to write single file components in. Vue file format. A single file component file has three parts: template, script, and style. The Vue loader module allows webpack to extract and process each part using a separate loader module, such as sass or SCSS loader. This setting allows us to write programs seamlessly using. Vue files.

The Vue loader module also allows static resources to be treated as module dependencies and to be processed using the webpack loader. It also allows for hot reloading during development.

4. What is mixin?

Mixins enables us to write pluggable and reusable features for Vue components. If you want to reuse a set of component options between multiple components, such as lifecycle hooks, methods, etc., you can write it as mixins and simply reference it in the component. Then merge the contents of mixin into the component. If you want to define a lifecycle hook in mixin, it will take precedence over the component’s own hook when executed.

5. During development, if your Vue program and back-end API server are not running on the same host, how to proxy API requests. Suppose you use vue-cli 3 for setup?

Let’s say we have a Node.js backend server running on localhost:4040. To ensure it is proxyed in and accessible from the components, we can configure the vue.config.js file and include a devServer section as shown below:

Suppose we have a node. JS back-end server running on localhost: 4040. To ensure that the agent can be accessed from the component, configure the vue.config.js file and include the devserver section as follows:

In the vue.config.js file:

module.exports: {
    devServer: {
        proxy: {
            '/api': { 
                target: ‘http://localhost:4040/api’, 
                changeOrigin: true 
            }
        }
    }
}

6. How does prop specify its type requirements?

By implementing the prop verification option, you can specify type requirements for a single prop. This has no impact on production, but warnings are issued during the development phase to help developers identify potential problems with specific types of requirements for incoming data and props.

To configure three props:

props: {
    accountNumber: {
        type: Number,
        required: true
    },
    name: {
        type: String,
        required: true
   },
   favoriteColors: Array
}

7. What is virtual DOM?

The document object model or DOM defines an interface that allows languages such as JavaScript to access and manipulate HTML documents. Elements are represented by nodes in the tree, and interfaces allow us to manipulate them. But this interface needs to pay a price. A large number of very frequent DOM operations will slow down the page speed.

Vue solves this problem by implementing the virtual representation of the document structure in memory, where the virtual node represents the node in the DOM tree. When manipulation is needed, computation and operation can be performed in the memory of the virtual DOM, rather than on the real dom. This is naturally faster and allows the virtual DOM algorithm to calculate the optimal way to update the actual DOM structure.

Once calculated, it is applied to the actual DOM tree, which improves performance, which is why virtual DOM based frameworks (such as Vue and react) are so prominent.

8. What is Vue plug-in?

The Vue plug-in allows developers to build global level functionality and add it to Vue. Use to add globally accessible methods and properties, resources, options, mixins, and other custom APIs to your program. Vuefire is an example of a Vue plug-in that adds firebase specific methods and binds them to the entire program. The firebase function can then be used anywhere in the program structurethisUsed in context.

9. What are rendering functions? for instance.

Vue allows us to build templates in a number of ways, the most common of which is to use only HTML with special instructions and mustache tags for response functions. But you can also use JavaScript to build templates using special function classes (called rendering functions). These functions are very close to the compiler, which means they are more efficient and faster than other template types. Because you use JavaScript to write rendering functions, you are free to use the language where you need to add custom functions directly.

It is very useful for advanced solutions of standard HTML templates.

Here is the Vue program using HTML as a template

new Vue({
  el: '#app',
  data: {
    fruits: ['Apples', 'Oranges', 'Kiwi']
  },
  template:
      `<div>
         <h1>Fruit Basket</h1>
         <ol>
           <li v-for="fruit in fruits">{{ fruit }}</li>
         </ol>
      </div>`
});

Here is the same program developed with rendering function:

new Vue({
  el: '#app',
  data: {
    fruits: ['Apples', 'Oranges', 'Kiwi']
  },
  render: function(createElement) {
    return createElement('div', [
      createElement('h1', 'Fruit Basket'),
      createElement('ol', this.fruits.map(function(fruit) { 
        return createElement('li', fruit); 
      }))
    ]);
  }
});

Output:

Fruit Basket

  1. Apples
  2. Oranges
  3. Kiwi

In the example above, we use a function that returns a series ofcreateElement()Call, each of which is responsible for generating an element. Although the V-for instruction works in HTML based templates, when using rendering functions, you can simply use the standard.map()Function to traverse the fruits data array.

10. Which lifecycle hook is most suitable for getting data from API calls?

Although this depends on the purpose and purpose of the component, the created life cycle hook is usually very suitable for placing API calls. You can use the data and responsiveness features of the component, but the component has not yet rendered.

11. When is the “updated” lifecycle hook called?

After the responsive data is updated and the virtual DOM is re rendered, the updated hook is called. It can be used to perform DOM related operations, but (by default) there is no guarantee that subcomponents will be rendered, although it can also be used in update functionsthis.$nextTickTo ensure that.

12. Why not use the arrow function when writing a lifecycle hook or other option / property in a Vue instance?

Arrow function is not defined by itselfthisContext, but bound to the context of its parent function. When you use arrow function in Vue program(=>WhenthisKeyword disease is not bound to a Vue instance, so an error is raised. Therefore, it is strongly recommended to use the standard function declaration instead.

13. When do I use the keep alive element?

When components are dynamically switched due to data attributes or some other response state, they are re rendered each time they are switched to the render state. Although you may need this behavior, re rendering may not be appropriate in some cases. For example, components that introduce data from API calls at creation time. You may not want to call this API every time you dynamically switch this component for rendering. You can then include the component in the keep alive element. The keep alive element caches the component and gets it from there, rather than re rendering it every time.

14. What is the recommended way to manage state in a large Vue program? Why?

As programs grow in function and code, state management becomes difficult, and using endless downstream network props and upstream events is certainly not a wise decision. In this case, it is necessary to transfer state management to the central management system. Vuex is provided in the Vue ecosystem, which is the official state management library and the recommended mode for centralized state storage.

Vuex allows maintenance of the central state. Component uses vuex as a responsive data store and updates when the status updates. Multiple or unrelated components can depend on the same central storage.

In this case, Vue acts as the pure view layer. To modify the state, the view layer, such as a button or interactive component, needs to issue a vuexAction, and then perform the required tasks. To update or modify the status, vuex providesMutations

The purpose of this workflow is to leave a trail of available operations.

15. What is asynchronous component?

When a large program uses a large number of components, it may not make sense to load all components from the server at the same time. In this case, Vue allows us to define components that are loaded asynchronously from the server when needed. When declaring or registering a component, Vue accepts the factory function that provides promise. You can then “parse” the component when it is called.

By loading only the basic components and delaying the loading of asynchronous components to the future call time, the bandwidth and program loading time can be saved.

This is a simple example of an asynchronous component.

new Vue({
    components: {
        ‘tweet-box’: () => import(‘./components/async/TweetBox’)
    }
}); 

When used in this way, webpack’s code splitting will be used to provide this functionality.


Welcome to other great articles in this column:

  • Deep understanding of shadow DOM v1
  • Step by step to teach you how to use webvr to realize virtual reality games
  • 13 modern CSS frameworks to improve your development efficiency
  • Get started bootstrap Vue
  • How does the JavaScript engine work? Everything you need to know from call stack to promise
  • Websocket practice: real time communication between node and react
  • 20 interview questions about Git
  • In depth analysis of console.log of node.js
  • What is node.js?
  • Build an API server with node.js in 30 minutes
  • Object copy of JavaScript
  • Programmers can’t earn 30K a month before they are 30 years old. Where to go
  • 14 best JavaScript data visualization Libraries
  • 8 top level vs code extensions for the front end
  • Node.js multithreading full guide
  • Four schemes and implementation of transforming HTML into PDF

  • More articles