Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The latest vue interview questions for 2021 are collated


May 30, 2021 Article blog


Table of contents


First, the understanding of MVVM

MVVM is divided into Model, View, ViewModel.

Model stands for data model, and data and business logic are defined in the Model layer;

View stands for UI view and is responsible for the presentation of data; The front end is primarily built by HTML and CSS.

ViewModel is responsible for listening for data changes in Model and controlling view updates and handling user interactions;

Model and View are not directly related, but are contacted through ViewModel, which has a two-way data binding relationship. S o when the data in Model changes, a refresh of the View layer is triggered, and the data in the View that changes due to user interaction is synchronized in Model. +

This mode enables model and View data to be automatically synchronized, so developers only need to focus on maintaining the data without having to dom themselves.

ViewModel is a layer of view data that is generated and maintained by a front-end developer organization. A t this level, the front-end developer transforms the Model data obtained from the back end and does a secondary encapsulation to generate a view data model that meets the view layer's usage expectations. I t is important to note that the data model encapsulated by ViewModel consists of the state and behavior of the view, while the model layer's data model contains only states, such as what happens when this piece of the page is loaded in, what happens when the page is loaded in, what happens by clicking on this block, what happens when the block scrolls is all view behavior (interaction), and view state and behavior are encapsulated in ViewModel. This encapsulation allows ViewModel to describe the View layer in its entirety.

The MVVM framework enables two-way binding so that ViewModel's content is presented in real time at the View layer, front-end developers no longer have to inefficiently and hassle to update the view by manipulating the DOM, the MVVM framework has done the dirtiest and most tiring piece, we developers only need to process and maintain ViewModel, update the view of the data will be automatically updated accordingly. This way, the View layer presents not the Model layer's data, but viewModel's data, which is the viewModel's responsibility to interact with the Model layer, which completely decouples the View layer and the Model layer, which is critical and is an important part of the implementation of the front-end separation scenario.

Second, vue common instructions

1. v-text

v-text is primarily used to update textContent and can be equivalent to the text property of JS.

<span v-text="msg"></span>

The two are equivalent:

<span>插值表达式{{msg}}</span>

2. v-html

The double braces interpret the data as plain text, not HTML. I n order to output real HTML, you can use the v-html directive. It is equivalent to the innerHtml property of JS.


<div v-html="rawHtml"></div>

The content of this div will be replaced with the property value rawHtml, rendered directly as HTML.

3. v-pre

v-pre is primarily used to skip this element and its child element compilation process. C an be used to display the original Mustache label. Skip a large number of nodes without instructions to speed up compilation.

<div id="app">
    <span v-pre>{{message}}</span>  //这条语句不进行编译
    <span>{{message}}</span>
</div>

Eventually, only the contents of the second span are displayed

4. v-cloak

This instruction is used to keep the element on until the end of the associated instance to compile.

<div id="app" v-cloak>
    <div>
        {{message}}
    </div>
</div>
<script type="text/javascript">
    new Vue({
      el:'#app',
      data:{
        message:'hello world'
      }
    })
</script>

Flashes when the page loads (interpolation flashing problem), starting with:

<div>
    {{message}}
</div>

Before it compiles as:

<div>
    hello world!
</div>

You can solve the problem of interpolation expression flickering with the v-cloak instruction, v-cloak in css with the property selector set to display: none;

5. v-once

V-once-associated instances that render only once. After the re-rendering, all child nodes of the instance are treated as static content skips, which can be used to optimize update performance.

<span v-once>This will never change:{{msg}}</span>  //单个元素
<div v-once>//有子元素
    <h1>comment</h1>
    <p>{{msg}}</p>
</div>
<my-component v-once:comment="msg"></my-component>  //组件
<ul>
    <li v-for="i in list">{{i}}</li>
</ul>

In the example above, msg, list does not re-render even if it changes.

6. v-if

v-if enables conditional rendering, and Vue renders elements based on the true and false conditions of the expression's value.

<a v-if="ok">yes</a>

If the property value ok is true, it is displayed. Otherwise, the element is not rendered.

7. v-else

v-else is used with v-if and must be immediately behind v-if or v-else-if, otherwise it does not work.

<a v-if="ok">yes</a>
<a v-else>No</a>

8. v-else-if
v-else-if acts as an else-if block for v-if and can be used in a chain multiple times. Switch statements can be implemented more easily.

<div v-if="type==='A'">
    A
</div>
<div v-else-if="type==='B'">
    B
</div>
<div v-else-if="type==='C'">
    C
</div>
<div v-else>
    Not A,B,C
</div>

9. v-show

<h1 v-show="ok">hello world</h1>

It is also used to present elements according to conditions. U nlike v-if, if the value of v-if is false, the element is destroyed and is not in the dom. However, the elements of v-show are always rendered and saved in dom, simply switching the dispaly properties of css.

Note: v-if has a higher switching overhead v-show has a higher initial rendering overhead. Therefore, it is better to use v-show if you want to switch very frequently, and v-if is better if the runtime conditions are unlikely to change

10. v-for
Render with the v-for instruction based on the traversal array
There are two forms of traversal

<div v-for="(item,index) in items"></div>   //使用in,index是一个可选参数,表示当前项的索引
<div v-for="item of items"></div>   //使用of

Here is an example, and in v-for, you have full access to the parent scope property.

<ul id="app">
    <li v-for="item in items">
        {{parent}}-{{item.text}}
    </li>
</ul>
<script type="text/javascript">
    var example = new Vue({
      el:'#app',
      data:{
        parent:'父作用域'
        items:[
          {text:'文本1'},
          {text:'文本2'}
        ]
      }
    })
</script>

will be rendered as:

<ul id="app">
    <li>父作用域-文本1</li>
    <li>父作用域-文本2</li>
</ul>
Note: When v-for and v-if are on the same node, v-for takes precedence over v-if. This means that v-if will run in each v-for loop

11. v-bind

v-bind is used to dynamically bind one or more attributes. W hen there are no parameters, you can bind to an object that contains a pair of key values. O ften used to dynamically bind class and style. a nd href, etc. In short, it's a colon:

< 1> object syntax:

//进行类切换的例子
<div id="app">
    <!--当data里面定义的isActive等于true时,is-active这个类才会被添加起作用-->
    <!--当data里面定义的hasError等于true时,text-danger这个类才会被添加起作用-->
    <div :class="{'is-active':isActive, 'text-danger':hasError}"></div>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            isActive: true,  
            hasError: false
        }
    })
</script>

Rendering results:

<!--因为hasError: false,所以text-danger不被渲染-->
<div class = "is-active"></div>

< 2> array syntax

<div id="app">
    <!--数组语法:errorClass在data对应的类一定会添加-->
    <!--is-active是对象语法,根据activeClass对应的取值决定是否添加-->
    <p :class="[{'is-active':activeClass},errorClass]">12345</p>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            activeClass: false,
            errorClass: 'text-danger'
        }
    })
</script>

Rendering results:

<!--因为activeClass: false,所以is-active不被渲染-->
<p class = "text-danger"></p>

< 3 > bind data objects directly

<div id="app">
    <!--在vue实例的data中定义了classObject对象,这个对象里面是所有类名及其真值-->
    <!--当里面的类的值是true时会被渲染-->
    <div :class="classObject">12345</div>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            classObject:{
                'is-active': false,
                'text-danger':true
            }           
        }
    })
</script>

Rendering results:

<!--因为'is-active': false,所以is-active不被渲染-->
<div class = "text-danger"></div>

12. v-model
This directive is used to create a two-way data binding on a form.
v-model ignores the initial values of the value, checked, selected attributes of all form elements. Because it selects the Vue instance data as the specific value.

<div id="app">
    <input v-model="somebody">
    <p>hello {{somebody}}</p>
</div>
<script>
    var app = new Vue({
        el: '#app',
        data: {
            somebody:'小明'
        }
    })
</script>

In this example, enter a different name directly in the browser input, and the following p content changes directly. This is bidirectional data binding.

v-model modifier .lazy by default, v-model syncs the values and data of the input box. This modifier allows you to convert to resynchronization in the change event.

<input v-model.lazy="msg">

<2> .number
Automatically converts the user's input values into numeric types

<input v-model.number="msg">

<3> .trim
The first and last spaces entered by the user are automatically filtered

<input v-model.trim="msg">

13. v-on
v-on is primarily used to listen for dom events in order to execute some blocks of code. An expression can be a method name.
The shorthand is as @

<div id="app">
    <button @click="consoleLog"></button>
</div>
<script>
    var app = new Vue({
        el: '#app',
        methods:{
            consoleLog:function (event) {
                console.log(1)
            }
        }
    })
</script>

Event modifier

  • .stop prevents the event from continuing to propagate
  • .prevent event no longer overloads the page
  • .capture uses the event capture pattern, where events triggered by the element itself are processed here before being processed by internal elements
  • .self triggers the handler only when event.target is the current element itself
  • .once event will only be triggered once
  • .passive tells the browser that you don't want to block the default behavior of the event
<!-- 阻止单击事件继续传播 -->
<a v-on:click.stop="doThis"></a>
 
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>
 
<!-- 修饰符可以串联 -->
<a v-on:click.stop.prevent="doThat"></a>
 
<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>
 
<!-- 添加事件监听器时使用事件捕获模式 -->
<!-- 即元素自身触发的事件先在此处处理,然后才交由内部元素进行处理 -->
<div v-on:click.capture="doThis">...</div>
 
<!-- 只当在 event.target 是当前元素自身时触发处理函数 -->
<!-- 即事件不是从内部元素触发的 -->
<div v-on:click.self="doThat">...</div>
 
<!-- 点击事件将只会触发一次 -->
<a v-on:click.once="doThis"></a>
 
<!-- 滚动事件的默认行为 (即滚动行为) 将会立即触发 -->
<!-- 而不会等待 `onScroll` 完成  -->
<!-- 这其中包含 `event.preventDefault()` 的情况 -->
<div v-on:scroll.passive="onScroll">...</div>

When you use modifiers, order is important; Therefore, using v-on:click.prevent.self blocks all clicks, while v-on:click.self.prevent only blocks clicks on the element itself.

3, v-if and v-show what's the difference?

Common ground: v-if and v-show enable the display of elements to be hidden

distinguish:

1. v-show is simply the display property of the control element, while v-if is the conditional rendering (the condition is true, the element will be rendered, the condition is false, the element will be destroyed);

2. v-show has a higher first rendering overhead, while v-if has a much smaller first rendering overhead;

3. v-if has a higher switching cost, v-show switching cost is small;

4. v-if has matching v-else-if and v-else, while v-show does not

5. v-if can be used with template, but v-show is not

Vue core idea: data-driven, component

1, data-driven

Traditional front-end data interactions use Ajax to get data from the service side and then manipulate the DOM to change the view, or the front-end interaction to change the data again, and manually manipulating the DOM is a tedious and error-prone process. V ue .js is a Javascript library that provides MVVM-style two-way data binding, focusing on the View layer. I t eliminates the need for developers to eliminate the need to change data by eliminating the process of manipulating the DOM. V ue encapsulates the DOM through the Dircetives directive, notifying the instruction to modify the corresponding DOM when the data changes, and the data-driven DOM changes, which is a natural mapping of the data. V ue also monitors operations, and when the view changes, vue listens to those changes, changing the data, creating a two-way binding of the data. V ue is an MVVM framework. D oM, on the other hand, is a natural mapping of data. T he traditional pattern is to request data from model via Ajax request, and then manually trigger the DOM to pass in the data to modify the page. I n Vue, Directives encapsulates the view, and when the data in the model changes, Vue modifies the DOM through the Directives directive. At the same time, doM Listener also implements the monitoring of view view, when the DOM changes, it is listened to, the model changes, and the data is bound in both directions.

2, component response principle data (model) change driver view (view) automatic update

When you pass a normal JavaScript object to the Vue instance's data option, Vue traverses all the properties of the object and uses Object.defineProperty to turn them all into getter/setter. O bject.defineProperty is a feature in ES5 that doesn't allow shim, which is why Vue doesn't support IE8 and earlier browsers. U sers don't see getter/setter, but internally they let Vue track dependencies and notify them of changes when properties are accessed and modified. T he problem to note here is that the browser console formats getter/setter differently when printing data objects, so you may need to install vue-devtools for a more user-friendly checking interface. Each component instance has a corresponding watcher instance object that records the property as a dependency during component rendering, and then notifies the watcher of the recalculation when the setter of the dependency is called, causing the components associated with it to be updated.

3, componentization

Extend HTML elements to encapsulate reusable code. E ach component corresponds to a ViewModel. E ach separate visual/interactive area on the page can be considered a component. E ach component corresponds to an engineering catalog in which the various resources required for the component are maintained. A page is a container for a component that can be nested and freely combined to form a complete page.

Componentization enables extended HTML elements to encapsulate the available code. Each individual visual/interactive area on the page is treated as a component; each component corresponds to an engineering directory in which the various resources required for the component are maintained nearby; and the page is simply a container of components that can be nested and freely combined to form a complete page.

V. V. Vue life cycle

 The latest vue interview questions for 2021 are collated1

Why is data a function in a component?

Why does data in a component have to be a function, and then return an object, and in the new Vue instance, data can be directly an object?

// data
data() {
  return {
	message: "子组件",
	childName:this.name
  }
}
 
// new Vue
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {App}
})

Because components are used for reuse, and objects in JS are reference relationships, if data in a component is an object, then the scope is not isolated, the data property values in the subcompletes affect each other, if the data option in the component is a function, then each instance can maintain a separate copy of the returned object, the data property values between the component instances do not affect each other;

7. What are the ways in which Vue components communicate between components?

Vue Intercommunication is one of the knowledge points of the interview, which is a bit like an open question, and the more methods you answer, the more points you add, indicating that you are more proficient with Vue. Vue component-to-component communication refers to the following three types of communication: parent-child component communication, intergenerational component communication, brother component communication, and below we describe each mode of communication and explain which type of component-to-component communication this method can be applied to.

(1) props / $emit for parent-child component communication

This approach is the foundation of the Vue component and is believed to be heard and heard by most of the students, so the examples are not covered here.

(2) ref communicates with the parent and child components of the $parent/$children

  • ref: If used on a normal DOM element, the reference points to the DOM element;
  • $parent/$children: Access parent/child instances

(3) EventBus ($emit / $on) is suitable for parent-child, intergenerational, and brother component communication

This approach uses an empty Vue instance as a central event bus (event hub) to trigger events and listen for events, enabling communication between any component, including parent-child, intergenerational, and sibling components.

(4) $attrs/$listeners for intergenerational component communication

  • $attrs: Contains attribute bindings (except class and style) that are not recognized (and acquired) by prop in the parent scope. W hen a component does not declare any props, it contains bindings for all parent scopes (except class and style), and internal components can be passed in through v-bind""$attrs". Usually used in conjunction with the inheritAttrs option.
  • $listeners: Contains the v-on event listener in the parent scope (without the .native decorator). It can be passed in to internal components through v-on "$listeners"

(5) provide /inject is suitable for intergenerational component communication

The variable is provided through provider in the ancestor component, and then injected into the variable in the child component. The provide/inject API primarily addresses communication between cross-level components, but its use scenario is primarily when subcommands acquire the state of the parent component, creating an active-provide and dependency-injection relationship between the cross-level components.

(6) Vuex is suitable for parent-child, intergenerational, and brother component communication

Vuex is a state management model developed specifically for Vue .js applications. A t the heart of every Vuex application is the store. "Store" is basically a container that contains most of the state in your app.

  • Vuex's state store is responsive. When a Vue component reads a state from the store, if the state in the store changes, the corresponding component is updated efficiently accordingly.
  • The only way to change the state in the store is to explicitly commit (commit) mutation. This makes it easy to track changes in each state.

Eight, the difference between computed and watch and the use of the scene?

computed: is a calculated property that relies on other property values, and the value of the computed is cached, and the value of the computed is recalculated the next time the value of the computed is obtained, and watch: it is more of an "observation" function, similar to a listening callback for some data, which performs a callback for subsequent operations whenever the monitored data changes;

  • Computed should be used when we need numerical calculations and rely on other data, because the caching characteristics of computed can be used to avoid recalculation every time a value is obtained;
  • When we need to perform asynchronous or expensive operations as data changes, we should use watch, which allows us to perform asynchronous operations (access an API), limit how often we can perform that operation, and set the intermediate state before we get the final result. These are calculation properties that cannot be done.

Nine, virtual DOM

merit:

  • Guaranteed performance floor: The virtual DOM of the framework needs to be adapted to any operations that may be generated by the upper-level API, and some of its DOM operations must be implemented as universal, so its performance is not optimal;
  • No need to manually manipulate doM: We no longer need to manually manipulate DOM, we just need to write the code logic of View-Model, and the framework will help us update the view in an expected way based on virtual DOM and data two-way binding, greatly improving our development efficiency;
  • Cross-platform: Virtual DOMs are essentially JavaScript objects, while DOMs are strongly platform-dependent, compared to virtual DOMs that make it easier to operate across platforms, such as server rendering, weex development, and so on.

shortcoming:

  • Unable to optimize the ultimate: While virtual DOMs are reasonably optimized to meet the performance needs of most applications, virtual DOMs cannot be optimized in targeted extremes in some applications where performance is critical.

Virtual DOM implementation principle:

The implementation of virtual DOM consists of three main parts:

  • Simulate the real DOM tree with JavaScript objects and abstract the real DOM;
  • diff algorithm - compare the differences between two virtual DOM trees;
  • pach algorithm - Applies the differences between two virtual DOM objects to the real DOM tree.

Ten, vue-router routing patterns are several?

  1. Hash Use the hash value of the URL as a route. All browsers are supported.
  2. History HTML5 History API and server configuration since. Refer to HTML5 History mode on the official website
  3. Abstract Supports all javascript modes. If no browser API is found, the route is automatically forced into this mode.

Eleven, delete, and Vue.delete delete arrays are different

Delete simply changes the key value of the deleted element to the other element of empty/undefined or remains the same. Vue.delete directly deleted the array and changed the key value of the array.

XII, SPA single page understanding, its advantages and disadvantages are what?

SPA (single-page application) loads HTML, JavaScript, and CSS only when the Web page is initialized. O nce the page load is complete, spa does not reload or jump the page because of the user's actions; merit:

  • User experience is good, fast, content changes do not need to reload the entire page, avoid unnecessary jumps and repeated rendering;
  • Based on the above point, SPA is less stressful to the server;
  • The front end responsibilities are separated, the architecture is clear, the front end interacts with logic, and the back end is responsible for data processing;

shortcoming:

  • The initial load takes a lot of time: in order to realize the function and display effect of single-page web application, JavaScript and CSS need to be loaded uniformly when the page is loaded, and some pages need to be loaded on demand;
  • Forward back routing management: Because a single-page app displays all the content in one page, it cannot use the browser's forward-back feature, and all page switching requires its own stack management;
  • SEO is difficult: because everything is dynamically displayed in one page, it has a natural disadvantage on SEO.

Thirteen, a brief description of Vue's responsive principle

When a Vue instance is created, vue traverses the properties of the data option, turns them into getter/setters with Object.defineProperty, and tracks the dependencies internally, notifying them of changes when the properties are accessed and modified. Each component instance has a corresponding watcher program instance that records properties as dependencies during component rendering, and then notifies the watcher of the recalculation when the setter of the dependency is called, causing its associated components to be updated.

 The latest vue interview questions for 2021 are collated2

How to implement a two-way data binding within a component in Vue?

Suppose you have an input box component that, when entered by the user, synchronizes the data in the parent component page with the specific idea that the parent component passes values to the child component through props, and the child component informs the parent component to modify the corresponding props value by $emit, as follows:

import Vue from 'vue'
 
const component = {
  props: ['value'],
  template: `
    <div>
      <input type="text" @input="handleInput" :value="value">
    </div>
  `,
  data () {
    return {
    }
  },
  methods: {
    handleInput (e) {
      this.$emit('input', e.target.value)
    }
  }
}
 
new Vue({
  components: {
    CompOne: component
  },
  el: '#root',
  template: `
    <div>
      <comp-one :value1="value" @input="value = arguments[0]"></comp-one>
    </div>
  `,
  data () {
    return {
      value: '123'
    }
  }
})

As you can see, when data is entered, the data in the parent-child component changes synchronously:

 The latest vue interview questions for 2021 are collated3

 The latest vue interview questions for 2021 are collated4

We did two things in the parent component, one was to pass props to the child component, and the other was to listen for input events and synchronize our value properties. S o can these two steps be streamlined a little bit? The answer is yes, you only need to modify the parent component:

template: `
    <div>
      <!--<comp-one :value1="value" @input="value = arguments[0]"></comp-one>-->
      <comp-one v-model="value"></comp-one>
    </div>
  `

v-model will actually help us with the two steps above.

XV. How do I monitor changes in a property value in Vue?

For example, you now need to monitor changes in data, obj.a. In Vue, you can monitor changes in object properties as such:

watch: {
      obj: {
      handler (newValue, oldValue) {
        console.log('obj changed')
      },
      deep: true
    }
  }

The deep property represents a deep traversal, but writing like this monitors all property changes in obj, which is not the effect we want, so make some modifications:

watch: {
   'obj.a': {
      handler (newName, oldName) {
        console.log('obj.a changed')
      }
   }
  }

There is another way, which can be done through computed, which requires only:

computed: {
    a1 () {
      return this.obj.a
    }
}

The properties of the calculated properties are implemented so that when the dependency changes, a new value is recalculated.

Recommended lessons: vue2.x micro-lesson, Vue project hands-on, Vue .js three-day hands-on tutorial