Vue interview questions are often asked in interviews

Passing friends, you can click a like, pay attention to ~~~

fromVue interview questions are often asked in interviews

Look at the interview questions just to fill in the gaps and see what you don’t know. Remember, don’t think that if you memorize the interview questions, everything will be ok. It’s better to understand the principles behind it, so that you can talk with confidence during the interview. Otherwise, a slightly skilled interviewer will be able to see if there is genuine talent or just memorize the interview question. (These are some basic VUE interview questions, don’t waste your time reading down)

I. Understanding of MVVM?


MVVM stands for model-view-ViewModel. The Model represents the data Model, where you can also define the business logic for data modification and manipulation. View represents the UI component that transforms the data model into a UI for presentation. A ViewModel listens for changes in Model data, controls the behavior of the View, and handles user interactions.

In MVVM architecture, there is no direct connection between View and Model, but interaction through ViewModel. The interaction between Model and ViewModel is bidirectional, so the changes of View data are synchronized to Model. Changes to Model data are immediately reflected in the View.

The ViewModel connects the View layer with the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic, do not need to manually manipulate DOM, do not need to pay attention to the synchronization of data state. Complex data state maintenance is managed entirely by MVVM.

Ii. Vue’s life cycle


  • beforeCreateData observation and initialization events have not yet started
  • createdAfter data observation, properties and methods, initialization events, the $EL property is not yet displayed
  • beforeMountCalled before the mount begins, the associated render function is called for the first time. The example completes the following configuration: compile the template, and generate HTML from the data inside the data and template. Note that the HTML has not been mounted to the page at this point.
  • mountedCalled after el is replaced by the newly created vm.$el and mounted to the instance. The example is configured to replace the DOM object pointed to by the EL attribute with the HTML compiled above. Finish rendering the HTML from the template to the HTML page. Ajax interactions occur during this process.
  • beforeUpdateCalled before data is updated and occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional rerendering.
  • updatedCalled after the virtual DOM has been re-rendered and patched due to data changes. When called, the component DOM is already updated, so DOM-dependent operations can be performed. In most cases, however, you should avoid changing the state during this period, as this can lead to an infinite update loop. This hook is not called during server-side rendering.
  • beforeDestroy(pre-destruction) called before instance destruction. The instance is still fully available.
  • destroyed(After destruction) called after the instance is destroyed. When called, all event listeners are removed and all subinstances are destroyed. This hook is not called during server-side rendering.

Some common questions:

1. What is the VUE lifecycle?

A: The lifecycle of a Vue instance is the process from creation to destruction. The life cycle of a Vue is a series of processes from the beginning of creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and destroying.

2. What is the role of the VUE lifecycle?

A: It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of the entire Vue instance.

3. How many phases are there in the VUE life cycle?

A: It can be divided into 8 stages altogether: before/after creation, before/after loading, before/after update, and before/after destruction.

4. Which hooks trigger the first page load?

A: Generates beforeCreate, created, beforeMount, mounted.

5. In which cycle is DOM rendering completed?

A: DOM rendering is done in Mounted.

3. Vue implements the principle of two-way data binding: Object.defineProperty ()


Vue implements bidirectional data binding mainly by using data hijacking combined with publiser-subscriber mode, hijacking setter and getter of each attribute through Object.defineProperty (), publishing messages to subscribers when data changes, and triggering corresponding listening callback. When passing an ordinary Javascript Object to a Vue instance as its data option, Vue iterates through its properties, turning them into getters/setters with Object.defineProperty. Getters/setters are invisible to the user, but internally they let Vue track dependencies and notify changes when properties are accessed and modified.

The two-way data binding of VUE takes MVVM as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor the data changes of its model, and uses Compile to parse and Compile template instructions (vUE is used to parse {{}}). Finally, watcher is used to build a communication bridge between observer and Compile to achieve data change – > view update; View Interactive Changes (INPUT) — > Data Model changes the bidirectional binding effect.

Js to achieve a simple two-way binding

<body>
    <div id="app">
    <input type="text" id="txt">
    <p id="show"></p>
</div>
</body>
<script type="text/javascript">
    var obj = {}
    Object.defineProperty(obj, 'txt', {
        get: function () {
            return obj
        },
        set: function (newValue) {
            document.getElementById('txt').value = newValue
            document.getElementById('show').innerHTML = newValue
        }
    })
    document.addEventListener('keyup', function (e) {
        obj.txt = e.target.value
    })
</script>
Copy the code

4. Parameter transfer between Vue components


Parent component to child component: the child component accepts data through the props method. Child component to parent: the $emit method passes arguments

2. Data transfer between non-parent components, the sibling component passes the value eventBus, which creates an event center, equivalent to a relay station, which can be used to transmit and receive events. This is suitable for small projects. (Although many people recommend using VUEX directly, depending on the demand. Technology is only the means, the end is king.

Vue routing implementation: Hash mode and history mode


Hash mode: In the browser, the symbol “#”, # and the characters after # are called hash, which is read with window.location.hash.

Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages. In hash mode, only the content before the hash symbol is included in the request, such as www.xxx.com. Therefore, the back end will not return a 404 error even if the route is not fully covered.

History mode: History uses new HTML5 features; Two new methods are provided: pushState (), replaceState () to modify the browser history stack, and popState events to listen for state changes.

In history mode, the URL of the front end must be the same as the URL of the back end, for example, www.xxx.com/items/id. The backend… /items/id route processing will return a 404 error. Vue-router’s official website states: “However, this mode needs to be configured in the background to play well… So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, it should return the same index.html page that your app depends on.”

Vue is different from Angular and React.


The following distinction may not be correct as the version is constantly being updated. I only use VUE in my work and am not familiar with Angular and React.

1. Differences from AngularJS

  • Similarities: all support instruction: built-in instruction and custom instruction; Both support filters: built-in filters and custom filters; Both support bidirectional data binding; None of them support low-end browsers.

  • Differences: AngularJS is expensive to learn, such as adding Dependency Injection, while vue.js provides simple and intuitive apis. In terms of performance, AngularJS relies on data being dirty checked, so the more Watcher you have, the slower it is; Vue.js uses dependency tracing based observations and uses asynchronous queue updates, where all data is triggered independently.

2. React

  • React uses a special JSX syntax, and Vue. Js is also used in component development. The central idea is the same: everything is a component, and component instances can be nested; Both provide reasonable hook functions that developers can customize to handle requirements; Do not build AJAX, Route and other functions into the core package, but in the way of plug-in loading; The feature of mixins is supported in component development.

  • React uses the Virtual DOM to do dirty checks on rendered results. Vue.js provides instructions and filters in the template, which can be very convenient and fast to operate Virtual DOM.

Vue route hook function


The home page can control navigation jump, beforeEach, afterEach, etc., generally used for page title modification. Some require login to adjust the page’s redirection function.

BeforeEach has 3 main parameters to, from, and next:

To: route The destination route object to be entered.

From: route Indicates the route that the current navigation is about to leave

Next: function must call the method resolve hook. The execution depends on the call parameters of the next method. You can control the jump of web pages.

What is VUex? How to use it? Which functional scenarios use it?


Reading-only states are concentrated in stores; The way to change that is to submit mutations, which is a simultaneous thing; Asynchronous logic should be encapsulated in actions.

Import store and inject in main.js. Create a new directory store… . Export.

The scenarios include: status between components, music playing, login status, and adding to shopping cart in a one-page application

state

  • Vuex uses a single state tree, where each application will contain only one store instance, but a single state tree is not incompatible with modularity. The state of the stored data cannot be modified directly.

mutations

  • Mutations defines a method that dynamically modifies the state or data in Vuex’s store.

getters

  • Vue-like computational properties, mainly used to filter some data.

action

  • Actions can be understood as a method that transforms the data in mutations into a method that can process data asynchronously. Simply speaking, it is an asynchronous manipulation of data. The View layer distributes actions through store.dispath.
const store = new Vuex.Store({ / / store instance
      state: {
         count: 0
             },
      mutations: {                
         increment (state) {
          state.count++
         }
          },
      actions: { 
         increment (context) {
          context.commit('increment')}}})Copy the code

When the modules project is particularly complex, each module can have its own state, mutation, action, and getters, which makes the structure very clear and easy to manage.

const moduleA = {
  state: {... },mutations: {... },actions: {... },getters: {... }}const moduleB = {
  state: {... },mutations: {... },actions: {... }}const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
})
Copy the code

Vue – CLI How to add custom commands?


1. Create local directives

var app = new Vue({
    el: '#app'.data: {},// Create directive (multiple)
    directives: {
        // Directive name
        dir1: {
            inserted(el) {
                // The first argument in the directive is the DOM of the directive currently in use
                console.log(el);
                console.log(arguments);
                // Manipulate the DOM
                el.style.width = '200px';
                el.style.height = '200px';
                el.style.background = '# 000'; }}}})Copy the code

2. Global instructions

Vue.directive('dir2', {
    inserted(el) {
        console.log(el); }})Copy the code

3. Use of instructions

<div id="app">
    <div v-dir1></div>
    <div v-dir2></div>
</div>
Copy the code

How does VUE customize a filter?


HTML code:

<div id="app">
     <input type="text" v-model="msg" />
     {{msg| capitalize }}
</div>
Copy the code

Js code:

var vm=new Vue({
    el:"#app".data: {msg:' '
    },
    filters: {
      capitalize: function (value) {
        if(! value)return ' '
        value = value.toString()
        return value.charAt(0).toUpperCase() + value.slice(1)}}})Copy the code

Globally defined filter

Vue.filter('capitalize'.function (value) {
  if(! value)return ' '
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)})Copy the code

The filter accepts the value of the expression (MSG) as its first argument. Capitalize filter will receive the value of MSG as the first parameter.

11. What do you know about Keep-alive?


Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.

After vue version 2.1.0, keep-alive added two new attributes: include(cache of included components) and exclude(exclude components are not cached and have a higher priority than include).

Method of use

<keep-alive include='include_components' exclude='exclude_components'>
  <component>
    <! -- Whether the component is cached depends on the include and exclude attributes -->
  </component>
</keep-alive>
Copy the code

Parameter interpretation

  • include– String or regular expression. Only components whose names match are cached
  • exclude– String or regular expression. Any component whose name matches will not be cached
  • includeexcludeProperty to allow components to cache conditionally. Both can use commas to separate strings, regular expressions, and arrays. Remember to use V-bind when using re’s or arrays.

Use the sample

<! -- Comma-separated strings, only components A and B are cached. -->
<keep-alive include="a,b">
  <component></component>
</keep-alive>

<! -- Regular expressions (you need to use V-bind, all matches will be cached) -->
<keep-alive :include="/a|b/">
  <component></component>
</keep-alive>

<! -- Array (need to use V-bind, include will be cached) -->
<keep-alive :include="['a', 'b']">
  <component></component>
</keep-alive>

Copy the code

12. Interview questions you can answer in one sentence


1. CSS only works on the current component

2. Difference between V-if and V-show

Answer: v-if is rendered according to conditions, v-show is block or none of display;

3.The difference between the router

A:The router is”Routing instance“Object includes route jump methods, hook functions, etc.

4. What are the two cores of vue.js?

A: Data-driven, component systems

5. Vue several common commands

Answer: V-for, V-if, V-bind, V-ON, V-show, V-else

6. What are the common modifiers of vue?

.prevent: Submit events that no longer reload the page; . Stop: prevents the click event from bubbling. .self: Fires when an event occurs in the element itself rather than a child element; .capture: event listening, called when an event occurs

7. Can V-ON bind multiple methods?

A: you can

8. What is the function of the key value in vUE?

A: When vue.js is updating a rendered element list with V-for, it defaults to a “reuse in place” policy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element here and make sure it shows every element that has been rendered under a specific index. The key’s main purpose is to update the virtual DOM efficiently.

9. What are the calculated attributes of vUE?

A: Putting too much logic into a template can make the template too heavy and difficult to maintain, so try to compute attributes in cases where complex processing of data is required and may be used multiple times. Benefits: (1) the data processing structure is clear; (2) Rely on data, data update, processing results automatically update; ③ Inside the attribute this points to the VM instance; (4) When template is called, write the calculation attribute name directly. ⑤ Commonly used is getter method, get data, can also use the set method to change the data; (6) Compared with methods, methods recalculates regardless of the dependent data. However, when the dependent data does not change, computed data is obtained from the cache and does not recalculate.

10. Vue and other single-page applications and their advantages and disadvantages

A: Pros: Vue aims to implement data binding and composite view components for responses through as simple an API as possible, with a data binding system for responses at its core. MVVM, data-driven, componentized, lightweight, simple, efficient, fast, module-friendly. Disadvantages: Does not support earlier versions of browsers, as low as IE9; Not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); The first time to load the home page is relatively long; You can’t use the browser’s navigation buttons. You need to move forward and backward.

11. How to define a vue-router dynamic route? How do I get the passed value

A: In the index.js file in the Router directory, add /:id to the path attribute, using the params.id of the Router object.