Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the interview questions for vue?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what are the interview questions for vue". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the interview questions for vue"?

1. Understanding of MVVM

MVVM is divided into Model, View and ViewModel.

Model stands for data model, and data and business logic are defined in the Model layer; generally, it refers to all kinds of business logic processing and data manipulation carried out by the back end, which is the api interface provided by the back end for the front end.

View represents the UI view and is responsible for the presentation of the data; the view layer, that is, the user interface. The front end is mainly built by HTML and CSS.

ViewModel is responsible for monitoring data changes in Model and controlling view updates, dealing with user interaction.

Model and View are not directly related, but are connected through ViewModel. There is a two-way data binding relationship between Model and ViewModel. Therefore, when the data in Model changes, the refresh of the View layer will be triggered, and the data changed in View due to user interaction will also be synchronized in Model. +

This mode enables automatic data synchronization between Model and View, so developers only need to focus on the maintenance of data, rather than operating dom themselves.

ViewModel is a view data layer generated and maintained by the front-end developer organization. In this layer, the front-end developers transform the Model data obtained from the back-end and re-encapsulate it to generate a view data model that meets the expectations of the View layer. It should be noted that the data model encapsulated by ViewModel includes the state and behavior of the view, while the data model of the Model layer only contains state, such as what this part of the page shows, what happens when the page loads, what happens when you click on this piece, and what happens when this piece scrolls. View state and behavior are encapsulated in ViewModel. This encapsulation allows ViewModel to fully describe the View layer.

MVVM framework implements two-way binding, so that the content of ViewModel will be displayed in the View layer in real time, front-end developers no longer have to inefficiently and troublesome to update the view by manipulating DOM, MVVM framework has done the dirtiest and most tiring part, we developers only need to deal with and maintain ViewModel, update the data view will be updated automatically. In this way, the View layer does not show the data of the Model layer, but the data of the ViewModel layer, and ViewModel is responsible for interacting with the Model layer, which completely decouples the View layer and the Model layer. This decoupling is very important, and it is an important part of the front and back end separation scheme.

2. Vue common instructions 1. V-text

V-text is mainly used to update textContent and can be equated with the text property of JS.

The two are equivalent:

Interpolation expression {{msg}} 2. V-html

The double curly braces interpret the data as plain text rather than HTML. To output the real HTML, you can use the v-html instruction. It is equivalent to the innerHtml property of JS.

The contents of this div will be replaced with the attribute value rawHtml, which will be rendered directly as HTML.

3. V-pre

V-pre is mainly used to skip the compilation of this element and its child elements. Can be used to display the original Mustache tag. Skip a large number of nodes without instructions to speed up compilation.

{{message}} / / this statement does not compile {{message}}

Finally, only the contents of the second span are displayed.

4. V-cloak

This directive is used to remain on the element until the end of the associated instance.

{{message}} new Vue ({el:'#app', data: {message:'hello world'}})

Flicker when the page is loaded (interpolation flicker problem), first display:

{{message}}

It is then compiled to:

Hello world!

You can use the v-cloak instruction to solve the flicker problem of interpolation expressions, and v-cloak is set to display: none in css using the property selector.

5. V-once

The instance associated with v-once is rendered only once. After re-rendering, the instance and all its child nodes will be treated as static content skips, which can be used to optimize update performance.

This will never change: {{msg}} / / single element / / comment with children

{{msg}}

/ / component {{I}}

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

6. V-if

V-if can achieve conditional rendering, and Vue renders elements according to the true or false conditions of the value of the expression.

Yes

Displayed if the property value ok is true. Otherwise, this element will not be rendered.

7. V-else

V-else is used with v-if, it must be immediately after v-if or v-else-if, otherwise it will not work.

YesNo

8. V-else-if

V-else-if acts as an else-if block for v-if and can be used chained multiple times. It is more convenient to implement switch statements.

A B C Not A,B,C

9. V-show

Hello world

It is also used to display elements according to conditions. Unlike v-if, if the value of v-if is false, the element is destroyed and is not in dom. But the elements of v-show are always rendered and saved in dom, which simply toggles the dispaly property of css.

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

10. V-for

Use the v-for command to render according to the traversal array

There are two forms of traversal

/ / use in,index is an optional parameter, indicating the index of the current item / / use of

The following is an example, and in v-for, you have full access to the parent scope properties.

{{parent}}-{{item.text}} var example = new Vue ({el:'#app', data: {parent:' parent scope 'items: [{text:' text 1'}, {text:' text 2'}]}})

Will be rendered as:

Parent scope-text 1 parent scope-text 2 Note: when v-for and v-if are on the same node, v-for has a higher priority than v-if. This means that v-if will run in 11. V-bind in each v-for loop

V-bind is used to dynamically bind one or more features. When there are no parameters, you can bind to an object that contains key-value pairs. Commonly used to dynamically bind class and style. And href and so on. Abbreviated as a colon [:]

Object syntax:

/ / example of class switching var app = new Vue ({el:'# app', data: {isActive: true, hasError: false}})

Render the result:

Array syntax

12345

Var app = new Vue ({el:'# app', data: {activeClass: false, errorClass: 'text-danger'}})

Render the result:

Bind data objects directly

12345 var app = new Vue ({el:'# app', data: {classObject: {'is-active': false,' text-danger':true})

Render the result:

12. V-model

This directive is used to create a two-way data binding on the form.

V-model ignores the initial values of the value, checked, and selected properties of all form elements. Because it chooses Vue instance data as the specific value.

Hello {{somebody}}

Var app = new Vue ({el:'# app', data: {somebody:' Xiaoming'}})

In this example, type a different name directly into the browser input, and the content of the following p will change directly. This is two-way data binding.

The v-model modifier. V-model synchronizes the values and data of the input box by default. You can use this modifier to resynchronize in the change event.

.number

Automatically convert the user's input value to a numeric type

.trim

Automatically filter leading and trailing spaces entered by the user

13. V-on

V-on is primarily used to listen for dom events in order to execute blocks of code. The expression can be a method name.

Abbreviated as: [@]

Var app = new Vue ({el:'# app', methods: {consoleLog:function (event) {console.log (1)})

Event modifier

.stop to stop the incident from spreading.

The .inherent event no longer reloads the page

.capture uses the event capture mode, where events triggered by the element itself are handled here before being handled by internal elements.

.self triggers the handler only when event.target is the current element itself.

The .once event will be triggered only once

.passive tells the browser that you don't want to block the default behavior of the event

.........

When using modifiers, order is important; the corresponding code is generated in the same order. Therefore, using v-on:click.prevent.self will block all clicks, while v-on:click.self.prevent will only block clicks on the element itself.

3. What's the difference between v-if and v-show?

What they have in common: both v-if and v-show can show and hide elements.

Difference:

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

2. V-show has higher first-time rendering overhead, while v-if 's first-time rendering cost is much lower.

3. V-if has higher handover overhead, while v-show has less handover overhead.

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

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

Fourth, the core idea of Vue: data-driven, component-based 1, data-driven.

The traditional front-end data interaction is to use Ajax to obtain data from the server, and then operate DOM to change the view; or when the front-end interaction wants to change the data, we have to do the above steps again, while manual operation of DOM is a tedious process and error-prone. Vue.js is a Javascript library that provides MVVM-style bidirectional data binding, focusing on the View layer. It saves developers the process of operating DOM and only needs to change the data. Vue will encapsulate the DOM through the Dircetives instruction. When the data changes, it will notify the instruction to modify the corresponding DOM, and the data-driven DOM changes. DOM is a natural mapping of the data. Vue also listens for operations, and when the view changes, vue monitors these changes, thus changing the data, thus forming a two-way binding of the data. Vue is a MVVM framework. DOM is a natural mapping of data. The traditional mode is to request data from model through an Ajax request, and then manually trigger the DOM to pass in the data to modify the page. In Vue, Directives encapsulates view. When the data in model changes, Vue modifies DOM through Directives instructions. At the same time, it also realizes the monitoring of the view view through DOM Listener. When the DOM changes, it will be monitored, realize the change of model, and realize the two-way binding of data.

2. Component response principle data (model) change driver view (view) automatic update

When you pass a normal JavaScript object to the data option of the Vue instance, Vue will iterate through all the properties of the object and use Object.defineProperty to convert all of these properties to getter/setter. Object.defineProperty is a feature of ES5 that cannot be shim, which is why Vue does not support IE8 and earlier browsers. Users do not see the getter/setter, but internally they let Vue track dependencies, notifying them of changes when properties are accessed and modified. The problem to note here is that the browser console does not format getter/setter differently when printing data objects, so you may need to install vue-devtools to get a more friendly check interface. Each component instance has a corresponding watcher instance object, which records the properties as dependencies during component rendering, and then tells watcher to recalculate when the dependency's setter is called, causing its associated components to be updated.

3. Componentization

Extend the HTML element to encapsulate reusable code. Each component corresponds to a ViewModel. Each separate visual / interactive area on the page can be treated as a component. Each component corresponds to a project directory, under which the various resources required by the component are maintained. A page is a container of components, and components can be nested and combined freely to form a complete page.

Componentization implements the extension of HTML elements to encapsulate available code. Each independent visual / interactive area on the page is regarded as a component; each component corresponds to a project directory under which all kinds of resources required by the component are maintained nearby; the page is just the container of the component. Components can be nested and freely combined to form a complete page.

V. Vue life cycle

Why is data a function in the component?

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

/ / datadata () {return {message: "subcomponents", childName:this.name}} / / new Vuenew Vue ({el:'# app', router, template:', components: {App}})

Because the component is used for reuse, and the object in the JS is a reference relationship, if the data in the component is an object, then the scope is not isolated, and the data attribute value in the subcomponent will influence each other. If the data option in the component is a function, then each instance can maintain an independent copy of the returned object, and the data property value between the component instances will not affect each other. Instances of new Vue are not reused, so there is no problem of referencing objects.

7. What are the ways to communicate between Vue components?

Communication between Vue components is one of the most common knowledge points in interviews. This question is a bit similar to open-ended questions. The more methods you answer, the more points you get, indicating that you are more proficient in Vue. Communication between Vue components only refers to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. Below, we will introduce each communication method and explain which type of component communication this method can be applied to.

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

This method is the basis of Vue components, and I believe most students will hear more about it, so I won't give an example to introduce it here.

(2) ref communicates with $parent / $children applicable parent-child components

Ref: if used on ordinary DOM elements, the reference points to the DOM element; if used on subcomponents, the reference points to the component instance

$parent / $children: access the parent / child instance

(3) EventBus ($emit / $on) is suitable for communication between father and son, intergenerational and sibling components.

This method uses an empty Vue instance as the central event bus (event center), which is used to trigger and listen for events, so as to realize the communication between any components, including parent-child, intergenerational, and sibling components.

(4) $attrs/$listeners is suitable for intergenerational component communication.

Attrs: contains feature bindings in the parent scope that are not recognized (and acquired by prop) (except class and style). When a component does not declare any prop, it contains bindings for all parent scopes (except class and style), and internal components can be passed in via vClure binding = "$attrs". It is usually used with the inheritAttrs option.

Listeners: contains the v-on event listeners in the parent scope (without the .native modifier). It can be passed into internal components via vMuon = "$listeners"

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

Variables are provided through provider in the ancestor component, and then injected into the descendant component through inject. Provide / inject API mainly solves the problem of communication between cross-level components, but its usage scenario is that sub-components obtain the status of superior components, and cross-level components establish a relationship between active provision and dependency injection.

(6) Vuex is suitable for communication between father and son, intergenerational and sibling components.

Vuex is a state management model developed specifically for Vue.js applications. The core of every Vuex application is store. "store" is basically a container that contains most of the state in your application.

The state storage of Vuex is responsive. When the Vue component reads the state from the store, if the state in the store changes, then the corresponding component will be updated efficiently accordingly.

The only way to change the state in store is to commit the mutation explicitly. This makes it easy for us to track changes in each state.

8. What is the difference and application scenario between computed and watch?

Computed: it is a computational attribute, which depends on other attribute values, and the value of computed is cached. Only when the value of the attribute it depends on changes, the value of computed will be recalculated the next time the value of computed is obtained. Watch: it is more like a "observation" function, similar to the listening callback of some data, which performs callbacks for subsequent operations whenever the monitored data changes. Use scenarios:

When we need to do numerical calculations and rely on other data, we should use computed because we can take advantage of the cache feature of computed to avoid having to recalculate every time we get a value.

When we need to perform asynchronous or expensive operations when the data changes, we should use watch, using the watch option to allow us to perform asynchronous operations (accessing an API), limit how often we perform the operation, and set the intermediate state before we get the final result. These are things that computational properties cannot do.

IX. Virtual DOM

Advantages:

Guarantee the lower limit of performance: the virtual DOM of the framework needs to adapt to any operations that may be generated by the upper API, and the implementation of some of its DOM operations must be universal, so its performance is not optimal; but its performance is much better than that of rough DOM operations, so the virtual DOM of the framework can at least guarantee good performance without manual optimization, that is, the lower limit of performance.

No need to operate DOM manually: we no longer need to manipulate DOM manually, we just need to write the code logic of View-Model. The framework will update our views in a predictable way according to virtual DOM and two-way binding of data, which greatly improves our development efficiency.

Cross-platform: virtual DOM is essentially a JavaScript object, while DOM is strongly related to the platform. Compared with virtual DOM, it is more convenient for cross-platform operations, such as server rendering, weex development, and so on.

Disadvantages:

Unable to carry out extreme optimization: although the reasonable optimization of virtual DOM + is sufficient to meet the performance needs of most applications, virtual DOM can not carry out targeted extreme optimization in some applications with high performance requirements.

The principle of virtual DOM implementation:

The implementation principle of virtual DOM mainly includes the following three parts:

Use JavaScript object to simulate the real DOM tree and abstract the real DOM

Diff algorithm-compare the differences between two virtual DOM trees

Pach algorithm-applies the difference between two virtual DOM objects to the real DOM tree.

How many vue-router routing patterns are there?

Hash: use the hash value of URL as the route. All browsers are supported.

History: since HTML5 History API and server configuration. Refer to the HTML5 History mode in the official website

Abstract: all javascript operating modes are supported. If an API without a browser is found, the route is automatically forced into this mode.

11. The difference between delete and Vue.delete delete array

Delete is just that the deleted element becomes the key value of other empty/undefined elements or remains the same. Vue.delete deletes the array directly and changes the key value of the array.

12. What are the advantages and disadvantages of SPA single page understanding?

SPA (single-page application) loads the corresponding HTML, JavaScript, and CSS only when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user's operation; instead, it will use the routing mechanism to achieve the transformation of HTML content, and the interaction between UI and users to avoid page reloading. Advantages:

The user experience is good and fast, and the change of content does not need to reload the entire page, avoiding unnecessary jump and repeated rendering.

Based on the above, SPA has relatively little pressure on the server

The front and rear end is responsible for the separation of responsibilities, the structure is clear, the front end carries on the interactive logic, and the back end is responsible for data processing.

Disadvantages:

The initial loading takes a lot of time: in order to achieve the application function and display effect of a single page Web, it is necessary to load JavaScript and CSS together when the page is loaded, and some pages are loaded on demand.

Forward and backward routing management: because a single page application displays all the content in a single page, you cannot use the browser's forward and backward function. All page switches need to establish stack management on their own.

SEO is more difficult: because all the content is dynamically replaced and displayed on one page, it has a natural weakness on SEO.

XIII. Briefly describe the responsive principle of Vue.

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

14. How to implement a bidirectional data binding within a component in Vue?

Suppose there is an input box component that synchronizes the data in the parent component page when the user enters it: the parent component passes the value to the child component through props, and the child component notifies the parent component to modify the corresponding props value through $emit. The specific implementation is as follows:

Import Vue from 'vue' const component = {props: [' value'], template: ``, data () {return {}}, methods: {handleInput (e) {this.$emit ('input', e.target.value)} new Vue ({components: {CompOne: component}, el:' # root', template:`` Data () {return {value: '123'}})

As you can see, when you enter data, the data in the parent and child components changes synchronously:

We do two things in the parent component, one is to pass props to the child component, and the other is to listen for input events and synchronize our own value properties. So can these two steps be further streamlined? The answer is yes, you just need to modify the parent component:

Template: ``

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

15. How to monitor the change of an attribute value in Vue?

For example, now you need to monitor the changes in obj.an in data. To monitor changes in object properties in Vue, you can do this:

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

The deep attribute represents a deep traversal, but writing this will monitor all property changes of the obj, which is not what we want, so make some changes:

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

There is another way to do this through computed, just:

Computed: {A1 () {return this.obj.a}}

Using the properties of the computed property, when the dependency changes, a new value is recalculated.

At this point, I believe you have a deeper understanding of "what are the interview questions of vue?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report