47 basic VueJS interview questions (with answers)

 

image

VueJS as a lightweight framework, Vue.js provides such powerful functions, which has attracted the attention of a large number of developers.

Nowadays, more companies are beginning to develop projects based on the Vue.js framework. Vue.js uses the features provided by EMAScript5 to implement data binding, provides component development, and helps speed up project development.

Like Angular and React, Vue.js includes data loss, two-way data binding, virtual DOM implementation, component development, life cycle, component communication, etc. These basic technologies are what developers should master.

1. What is the MVVM framework? What scenarios does it apply to?

The MVVM framework is a Model-View-View Model framework, where the ViewModel connects the model (Model) and the view (View).

In scenarios where there are more data manipulations, the MVVM framework is more suitable, which helps to render pages by manipulating data.

2. Which component attribute is active-class?

It is an attribute of the router-link component of the vue-router module.

3. How to define the dynamic routing of Vue-router?

Add a colon in front of the static route name, for example, set the id dynamic route parameter, and set /:id for the path attribute of the route object.

4. How to get the passed dynamic parameters?

In the component, use the params.id of the $router object, that is, $route.params.id.

5. What kind of navigation hooks does vue-router have?

There are 3 kinds.

The first is the global navigation hook: router.beforeEach(to,from,next). The function is to judge and intercept before jumping.

The second is the hook in the component.

The third type is a separate routing exclusive component.

6. What is mint-ui? how to use?

It is a front-end component library based on Vue.js. Install with npm, and then import styles and JavaScript code through import. vue.use(mintUi) is used to import globally, import {Toast} from'mint-ui' is used to import locally in a single component.

7. What is V-model? what's the effect?

v-model is an instruction in Vue.js, which can realize two-way binding of data.

8. How to bind events to tags in Vue.js?

There are two ways to bind events.

The first is through the v-on instruction, <input v-on:click= doLog()/>.

The second way, through @syntax sugar, <input@ click= doLog()/>.

9. What is vuex? how to use? In which functional scenarios is it used?

Vuex is a state management system implemented for the Vue.js framework.

In order to use vuex, store must be introduced and injected into the Vue.js component. The store object can be accessed through $ostore inside the component.

Usage scenarios include: in single-page applications, used for communication between components, such as music playback, login status management, and adding to shopping carts.

10. How to implement custom instructions? What hook functions does it have? What other hook function parameters?

Custom instructions include the following two types.

  • Global custom instructions: The vue.js object provides a directive method, which can be used to customize instructions. The directive method accepts two parameters, one is the name of the directive and the other is a function.

  • Local custom instructions: defined by the directives attribute of the component.

It has the following hook functions.

  • bind: Called when the directive is bound to the element for the first time.

  • inserted: called when the bound element is inserted into the parent node (new in Vue2.0).

  • update: called when the VNode of the component is updated.

  • componentUpdated: Called after the VNode and its sub-VNodes of the component where the instruction is located are all updated (new in Vue2.0).

  • unbind: Called only once, when the instruction is unbound from the element.

The parameters of the hook function are as follows.

  • el: The element bound by the instruction.

  • binding: instruction object.

  • vnode: virtual node.

  • oldVnode: The last virtual node.

11. Name at least 4 instructions in vue.js and their usage.

The related instructions and their usage are as follows.

  • v-if: Determine whether the object is hidden.

  • v-for: loop rendering.

  • v-bind: Bind an attribute.

  • v-model: to achieve two-way data binding.

12. What is Vue-router? What are its components?

It is a routing plugin for Vue.js. Components include router-link and router-vIew.

13. What are the navigation hooks? What are their parameters?

Navigation hooks, also known as navigation guards, are divided into global hooks, single-route exclusive hooks, and component-level hooks.

Global hooks include beforeEach, beforeResolve (new in Vue 2.5.0), and afterEach.

A single route exclusive hook has beforeEnter.

The component-level hooks include beforeRouteEnter, beforeRouteUpdate (new in Vue2.2) and beforeRouteLeave.

They have the following parameters.

  • to: The target routing object to be entered.

  • from: The route that the current navigation is about to leave.

  • next: This function must be used to reach the next route. If it is not used, it will be intercepted.

14. What is the principle of two-way data binding in Vue.js?

Vue. js uses the property features provided by ES5, combined with the publisher-subscriber model, defines get and set feature methods for each property through Object.defineProperty(), publishes messages to subscribers when data changes, and triggers corresponding monitoring Callback.

Specific steps are as follows.

(1) Recursively traverse the data objects that need to be observed, including the attributes of the sub-attribute objects, and set the set and get characteristic methods. When assigning a value to this object, the bound set characteristic method will be triggered, so the data change can be monitored.

(2) Use compile to parse the template instruction and replace the variables in the template with data. Then initialize the rendering page view, bind the update function to the node corresponding to each instruction, and add subscribers who monitor the data. Once the data changes, you will be notified and update the view

(3) Watcher subscribers are the communication bridge between Observer and Compile. The main functions are as follows.

  • Add yourself to the attribute subscriber (dep) when it is instantiated.

  • It must have an update() method.

  • When dep.notice() publishes a notification, it can call its own updat() method and trigger the callback function bound in Compile.

(4) MVVM is the entry point for data binding. It integrates Observer, Compile and Watcher. Observer is used to monitor changes in model data, Compile is used to parse and compile template instructions, and Watcher is used to establish the connection between Observer and Compile. Communication bridge, to achieve the effect of data change notification view update. Use view interaction to change and update the two-way binding effect of data model changes.

15. Please elaborate on your understanding of the life cycle of Vue.js.

There are 8 stages in total, namely beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroyed, and destroyed.

  • beforeCreate: After the instance is initialized, it is called before the data observer and event/watcher event configuration.

  • created: Called immediately after the instance is created. At this step, the instance has completed the following configurations: data observers, calculations of attributes and methods, and watch/event event callbacks. However, the mount phase has not yet started, and the $el attribute is currently not visible.

  • beforeMount: Called before the start of the mount, the related render function is called for the first time.

  • mounted: el is replaced by the newly created vm.$el, and the hook is called after it is mounted on the instance. If the root instance mounts an element in the document, vm.sel is also in the document when mounted is called.

  • beforeUpdate: Called when the data is updated, before the virtual DOM is re-rendered and patched.

  • updated: The virtual DOM is re-rendered and patched due to data changes, after which the hook will be called.

  • beforeDestroy: Called before the instance is destroyed. At this step, the instance is still fully available.

  • destroyed: Called after the Vue. js instance is destroyed. After the call, everything indicated by the Vue. js instance will be unbound, all event listeners will be removed, and all child instances will be destroyed.

When the kep-alive function of the component is used, the following two cycles are added.

  • activated is called when the keep-alive component is activated;

  • deactivated is called when the keep-live component is deactivated.

Vue 2.5.0 version adds a new cycle hook: ErrorCaptured, which is called when an error from a descendant component is captured.

16. Please describe the process of encapsulating Vue components.

Components can improve the development efficiency of the entire project, can abstract the page into multiple relatively independent modules, and solve the problems of low efficiency, difficult maintenance, and reusability in traditional project development.

Use the Vue.extend method to create a component, and use the Vue.component method to register the component. Sub-components need data and can receive data in props. After the child component modifies the data, if you want to pass the data to the parent component, you can use the emit method.

17. How did you meet vuex?

Vuex can be understood as a development model or framework. It is an extension of the data layer of the Vue.js framework. Centrally manage changes in drive components through state (data source). The state of the application is concentrated in the store. The way to change the state is to submit mutations, which is a synchronous transaction. Asynchronous logic should be encapsulated in action.

18. What is Vue-loader? What are its uses?

It is a loader that parses .vue files and can convert template/js/style into JavaScript modules.

The purpose is to write EMAScript 6 grammar through vue-loader, JavaScript, scss or less for style style, and jade grammar for template.

19. Please tell us the usage of each folder and file in the src directory of the vue.cli project.

The assets folder stores static resources; components stores components; router defines routing-related configurations; view is a view; app. vue is an application main component; main.js is an entry file.

20. How to use custom components in Vue.cli? What problems have you encountered during use?

Specific steps are as follows.

(1) Create a new component file in the components directory, and the script must export the exposed interface.

(2) Import the pages (components) that need to be used.

(3) Inject the imported components into the components property of the uejs sub-components.

(4) Use custom components in the template view.

21. Talk about your understanding of template compilation of vue.js.

In short, it is first converted into AST (Abstract Syntax Tree, abstract syntax tree), that is, the source code syntax structure is abstracted into a tree-like representation, and then rendered through the render function, and returned to VNode (Vue. js virtual DOM node ).

The detailed steps are as follows.

(1) The template is compiled into AST through the compile compiler, compile is the return value of create Compiler, and createCompiler is used to create the compiler. In addition, compile is also responsible for merging options.

(2) AST will get the render function through generate (the process of transforming AST into a render funtion string). The return value of render is VNode, which is a virtual DOM node of Vue.Js, which contains label name sub-nodes, text, etc.

22. Talk about the MVVM mode in Vue.js.

The MVVM model is the Model-View-ViewModel model.

Vue.js is data-driven. Vue.js instantiates the object to bind the DOM and data. Once bound, it will be synchronized with the data. Whenever the data changes, the DOM will also change.

ViewModel is the core of Vue.js, it is an instance of Vue.js. Vue.js will instantiate an HTML element. This HTML element can be the body or the element referred to by a CSS selector.

DOM Listeners and Data Bindings are the keys to two-way binding. DOM Listeners monitor all DOM elements in the View layer of the page. When changes occur, the data in the Model layer changes accordingly. Data Bindings monitors the data of the Model layer. When the data changes, the DOM elements of the View layer also change.

23. What is the difference between the v-show command and the v-if command?

Both v-show and v-if are conditional rendering instructions. The difference is that no matter the value of v-show is true or false, the element will exist in the HTML page; and only when the value of v-if is true, the element will exist in the HTML page. The v-show command is implemented by modifying the style attribute value of the element.

24. How to make CSS only work in the current component?

Each Vue.js component can define its own CSS and JavaScript code. If you want the CSS written in the component to only work on the current component, you only need to add the Scoped attribute to the Style tag, that is, <style scoped></style>.

25. How to create vue.js components?

In vue.js, components must be registered before they can be used. The specific code is as follows

<!--应用程序--><div id="app"><ickt></ickt></div><!--模板--><template id="demo"><!--模板元素要有同一个根元素--><div><h1>{
   
   {msg}}</h1></div></template><script type="text/javascript">//定义组件类var Ickt = Vue.extend ({
   
   template:'#demo',data:function(){
   
   return {
   
   msg:'有课前端网'}}})//注册组件Vue .component('ickt, Ickt)//定义Vue实例化对象var app= new Vue ({
   
   el:'#app',data:{}})</script>

26. How to realize routing nesting? How to perform page jump?

Routing nesting will render other components into this component, instead of making the entire page jump to the location where the router-view defines component rendering. To perform a page jump, the page must be rendered into the root component, which can be configured as follows.

new Vue({
   
   el:'#icketang', router:router, template:'<router-view></router-view>'})

First, instantiate the root component and define the component rendering container in the root component. Then, mount the route, and when the route is switched, the entire page will be switched.

27. What is the function of ref attribute?

Sometimes, in order to directly access some elements inside the component, you can define the attribute. At this time, you can access the element that sets the ref attribute more quickly through the this. $refs attribute inside the component. This is a native DOM element. Use native DOM API to manipulate them, for example, the following code.

 

<div id="icke">< span ref="msg">有课前端网</span>< span ref=" otherMsg">专业前端技术学习网校</span></div>app. $refs. msg. text Content//有课前端网app. $refs.otherMsg. textContent//专业前端技术学习网校

Note: In Ve2.0, the ref attribute replaces the function of the v-el instruction in version 1.0.

28. What is Vue.js?

Vue.js is a progressive framework for building user interfaces. Unlike other heavyweight frameworks, Vue.js adopts a bottom-up incremental development design. The core library of Vue.js only focuses on the view layer, and is easy to learn and easy to integrate with other libraries or existing projects. In addition, Vue.js is fully capable of driving complex single-page applications developed with single-file components and libraries supported by the Vue.js ecosystem.

The goal of Vue. js is to implement reactive data binding component development through the simplest possible API.

29. Describe some features of vue.js.

Vue.js has the following characteristics.

(1) MVVM mode.

When the data model (Model) changes, the view (View) listens to the change, and it also changes synchronously; when the view (View) changes, the data model (Model) listens to the change and also changes synchronously.

There are several advantages to using the MVVM model.

  • Low coupling, views can be independent of model changes and modifications. A View Model can be bound to different views. The model can be unchanged when the view changes, and the view can also be unchanged when the model changes.

  • Reusability, you can put some view logic in the ViewModel, allowing many views to reuse this view logic.

  • Independent development, developers can focus on business logic and data development. The designer can focus on the design of the view.

  • Testability, the view can be tested against the View Model.

(2) Component development

(3) Command system

(4) Vue2.0 began to support virtual DOM.

But in Vue1.0, real DOM elements are manipulated instead of virtual DOM, which can improve the rendering performance of the page.

30. Describe the characteristics of vue.js.

Vue. js has the following characteristics.

  • Concise: The page consists of HTML template + JSON data + Vue. js instantiated objects.

  • Data-driven: automatically calculate attributes and track dependent template expressions.

  • Componentization: Use reusable and decoupled components to construct pages.

  • Lightweight: The amount of code is small and does not rely on other libraries.

  • Fast: accurately and efficiently implement DOM updates in batches.

  • Easy to get: It can be installed through npm, bower and other methods, and it is easy to integrate.

31. How to bind events in vue.js?

The event is bound by the syntax of v-on followed by the event name="event callback function ()". The parameter set () of the event callback function is optional. If there is a parameter set (), the parameters of the event callback function need to be actively passed, and the event object needs to be passed $event. Of course, some other custom data can also be passed at this time. If there is no parameter set, then the event callback function has a default parameter, which is the event object. The event callback function should be defined in the methods attribute of the component, and the scope is the Vue. js instantiated object, so in the method, you can use the data and methods in Vue. js through this, or you can quickly bind the event through @ Grammar , Such as @event name="event callback function ()".

32. Please explain the role of the <keep-alive> component.

When <keep-alive> wraps dynamic components, inactive component instances are cached instead of destroying them.

<keep-alive> is an abstract component, it will not render a DOM element by itself, nor will it appear in the parent component chain.

When the component is switched within <keep-alive>, its two life cycle sub-functions, activated and deactivated, will be executed.

<keep-alive><component :is="view"></component></keep-alive >

33. What is axios? How to use it?

axios is a module used to replace the vue-resource.js plug-in in vue2.0, and it is a module for requesting the backend.

Install axios with npm install axios. Based on the EMAScript Module specification of EMAScript 6, import axios through the import keyword and add it to the prototype of the Vue.js class. In this way, every component (including vue.js instantiated objects) will inherit the method object. It defines methods such as get and post, which can send get or post requests. The callback function after successful registration in the then method can directly access the component instantiation object and store the returned data through the scope feature of the arrow function.

​​​​​​​

import Vue from ' vue' import axios from 'axios';Vue.prototype.$http=axios; new Vue ({
   
   el:' ickt',data:{
   
   msg:' '},template:'<h1> { { msg } }</h1>',created:function() {
   
   this.$http.get( 'data.json' ).then(res => {
   
   this. msg= res .data. data})}})

34. In axios, what is the operation performed when axios.post('api/user') is called?

When the post method is called, it means that a post asynchronous request is sent.

35. What is sass? How to install and use in ue?

Sass is a CSS pre-compiled language installation and use steps are as follows.

(1) Use npm to install the loader (sass-loader, css-loader, etc.).

(2) Configure the sass loader in webpack. config. js.

模块module:{
   
   //加载程序loaders:[//加载scss {
   
   test:/ \ .scss$ /, loader : 'vue-style-loader!css-loader!sass-loader '        }      ]}

(3) Add the lang attribute to the style tag of the component, for example, lang="scss".

<style type="text/css" lang="scss">$color:red; h1 {
   
   color: $color;}</style>

36. How to cyclically insert pictures in Vue. js?

Interpolating the "src" attribute will result in a 404 request error. The v-bind:src format should be used instead.

code show as below:

<ul class="list"><li v-for="item in list"><img :src=" 'img/' + item.url" alt="></1i></u1>

Note: Attribute interpolation is supported in vue1.0. In version 2.0, only the v-bind instruction or colon syntactic sugar ":" is allowed to realize dynamic binding of attributes.

37. How to customize the bound data value for the marquee element?

For radio buttons, the value is usually a static string. If the data bound to the v-model is equal to a certain value, the radio button is selected.

<1abe1>选择你喜欢的运动</1abe1><!--数据双向绑定--><label>篮球<input  type="radio"  v-model="sports"  value="basketball"></label><label>足球<input  type="radio"  v-model="sports"  value="football"></label><label>网球<input  type="radio"  v-model="sports"  value="netball"></label>

For multi-select boxes, the value of the v-model binding variable is usually a Boolean value, true means selected, and false means unselected. If you want to customize the value of the bound data, you need to use the v-bind command to set the true-value (value when selected) and false-value (value when not selected).

<1abe1>选择你的兴趣爱好</labe1><label>足球<input type="checkbox"  v-model="intrest. football"></label><label>篮球<input type="checkbox"  v-model="intrest. basketball"  v-bind:true-value=" trueValue" v-bind:false-value="falsevalue"></label>

38. Under what circumstances will fragment instances be generated?

In the following cases, the fragment instance template contains multiple top-level elements; the template only contains normal text; the template only contains other components (other components may be a fragment instance); the template contains only one element instruction, such as vue-router <router -view>; The root node of the template has a flow control instruction, such as v-if or v-for.

In these cases, the instance has an unknown number of top-level elements, and the template will treat its DOM content as fragments. The fragment instance will still render the content correctly. However, the template does not have a root node, and its $el points to an anchor node, which is an empty text node (a comment node in development mode).

Note: In Vue2.0, only one root node is allowed in the template of a component.

39. Realize multiple methods to display different characters according to different conditions.

Conditional selection can be achieved through the "v-if, v-else" instruction. However, if there are multiple consecutive condition selections, the calculated attribute needs to be used. For example, when no content is entered in the input box, the string "please enter content" is displayed; otherwise, the content in the input box is displayed. The code is as follows.

<div id="app"><input type="text  v-model="inputvalue"><hl>  {  { showValue } }</h1></div>var app = new Vue ( {
   
    e1:"#app', data:{
   
   inputvalue:'  'computed: {
   
    showValue:function ( ) {
   
   return this. inputvalue | | '请输入内容'       }}})

40. What is data loss?

If the data is not defined during initialization, the updated data cannot trigger the page rendering update. This part of the data is the missing data (because there is no set feature). This phenomenon is called data loss.

41. How to detect data changes?

Due to the limitation of JavaScript features, Vue.js cannot detect the changes in the following arrays, that is, the changed data in the following arrays is "lost".

Set elements by direct indexing, such as app.arr[0]=...

Modify the length of the data, such as app. arr.length.

In order to solve this problem, Vue.js extends the observation array and adds a $set() method to it. The array modified by this method can trigger the view update and detect data changes.

  •  
app.$set(app. arr, 5, 500);

42. How to detect object changes?

Due to the limitation of JavaScript features, Vue.js cannot detect the addition or deletion of object attributes. Because Vue.js converts properties to getter/setter during initialization, the properties must be defined in the data object so that Vue.js can convert it and make it respond during initialization, for example, the following code

var data ={
   
    obj:{
   
    a:1}}var app= new Vue ({
   
   el:'#app ',data:data })app.obj.a=10// 'app.obj.a'和'data.obj.a'现在是响应的app. obj. b=2//'app.obj.b'不是响应的data.obj.b=2//data.obj.b'不是响应的

If you need to add properties after the instance is created and make it respond, you can use the $set instance method.

app.$set(app.obj,'b',500)// 'app.obj.b'和'data.obj.b'现在是响应的

For ordinary data objects, you can use the global method Vue.set (object, key, value).

Vue.set(data.obj,"b',500)//'app.obj.b'和'cata,obj.b'现在是响应的

43. Talk about the flickering of the Vue.js page { {message}}.

Vue. js provides a v-cloak instruction, which remains on the element until the associated instance finishes compiling. When used with CSS, this directive can hide uncompiled tags until the completion of the instance compilation. The usage is as follows.

[v-cloak ]{
   
    display:none;}<div v-cloak> { { title } }</div>

This way <div> will not be displayed until the end of compilation.

44. How to realize the two-way binding of v-model data in the v-for loop?

Sometimes it is necessary to create inputs in a loop, and use the v-model to achieve two-way data binding. At this time, you can bind a member of the v-model array selected [$index], so that you can bind different v-models to different inputs, and then operate them separately.

<div v-for= " ( item, index ) in arr"><input type= "text "  v-model="arr [index ] "><h1> { { arr [index ] } } </h1></div>

45. How to solve the problem of too deep data hierarchy?

When developing a business, it often happens that data is obtained asynchronously, and sometimes the data level is deeper, such as the following code.

<span 'v-text="a.b.c.d"></span>

You can use vm.$set to manually define a layer of data.

vm.$set ("demo",a .b.c.d)

46. ​​How to solve the problem that the style coverage in the Vue.js file does not take effect?

According to the official statement of Vue. js, style plus scoped can make the style "privatized" (that is, it is only valid for the code in the current Vue.js file (component), not for the code in other files (components). Cause an impact)

Many times, we have introduced third-party UI, and style coverage in Vue.js files does not take effect. Most of the problems are caused by scoped on style.

The solution is to put this part of the code that needs to be covered into a separate CSS file, and finally import it in the main.js file.

47. How to avoid cross-domain when calling interfaces in the Vue.js development environment?

Configure the proxyTable item as follows in the project directory config/index.js.

​​​​​​​

proxyTable:{
   
   '/api ':{
   
   target:http://xxxxxx.com changeOrigin:true,pathRewrite:{
   
   '^/api':' '}}}

 

End of this article~

 

image

image

Guess you like

Origin blog.csdn.net/liuhao9999/article/details/114985458