Common interview questions of Vue

qqcc 2021-06-18 15:38:37
common interview questions vue


  1. Talk to you about MVVM Understanding of development patterns

    MVVM It is divided into Model、View、ViewModel The three .

Model: Representative data model , Data and business logic are in Model Defined in layer ;
View: representative UI View , Responsible for data presentation ;
ViewModel: Responsible for monitoring Model Change of data and control of view update , Dealing with user interaction ;

 Model and View There is no direct connection , But through ViewModel To make contact ,Model and ViewModel There is a two-way data binding relationship between . So when Model When the data in is changed, it will trigger View Layer refresh ,View The data changed due to user interaction will also be in Model Medium sync .

This pattern implements Model and View Automatic data synchronization , So developers just need to focus on data maintenance operations , And you don't have to operate it yourself dom.

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

    v-show Just control how elements are displayed , take display Attribute in block and none Switch back and forth ; and v-if Will control this DOM Whether the node exists or not . When we need to switch the display of an element often / When hidden , Use v-show It will save more on performance ; When you only need to show or hide once , Use v-if It is more reasonable .
    
  1. sketch Vue The principle of response

    Vue. js use ES5 Provide the property feature function , Combined with publisher - Subscriber pattern , adopt Object.defineProperty() Define for each attribute get、set Characteristic method , Post messages to subscribers when data changes , Trigger corresponding listening callback .
    

The specific steps are as follows .

(1) Recursive traversal of data objects to be observed , Include properties of child property objects , Set up set and get Characteristic method . When you assign a value to this object , Will trigger the binding set Characteristic method , So you can listen for data changes .

(2) use compile Parsing template instruction , Replace variables in the template with data . Then initialize render page view , And update the node binding function corresponding to each instruction , Add subscribers listening to data . Once the data changes , I'll be informed , And update the view

(3) Watcher Subscribers are Observer and Compile Communication bridge between , The main functions are as follows .

To the property subscriber when instantiating itself (dep) Add yourself to it .
You have to have a update( ) Method .
stay dep.notice() When a notice is issued , Can call its own updat() Method , And trigger Compile The callback function bound in .
(4)MVVM Is the entry to data binding , Integrated Observer、 Compile and Watcher The three , adopt Observer To spy on yourself model Data changes , adopt Compile To parse the compile template directive , In the end use Watcher Set up Observer and Compile Communication Bridges between , Achieve the effect of data change notification view update . Interact with views , Change update data model The effect of changing the two-way binding .

 image.png

4、 Please elaborate on your understanding of Vue.js Life cycle understanding .

The total is divided into 8 Stages , Respectively beforeCreate、created、beforeMount、 mounted、beforeUpdate、 updated、 beforeDestroyed、 destroyed.

beforeCreate: After the instance is initialized , Data observer ( data observer) and event/ watcher Call before event configuration .
created: Call... Immediately after the instance is created . In this step , The instance has completed the following configuration : Data observer , Operations on properties and methods , watch/event Event callback . However , The mount phase has not yet begun ,$el Properties are not currently visible .
beforeMount: It is called before the mount begins , dependent render Function first call .
mounted:    el Newly created vm.$el Replace , And after mounting to the instance, call the hook if root Instance mounts a document element , When calling mounted when vm.sel Also in the document .
beforeUpdate: Called when data is updated , It happened in the virtual world DOM Before re rendering and patching .
updated: Virtual due to data changes DOM Re rendering and patching , The hook is called after that .
beforeDestroy: Call before instance destruction . In this step , Instance is still fully available .
destroyed: stay Vue. js Call after instance destruction . After calling ,Vue. js Everything indicated by the instance is unbound , All event listeners will be removed , All child instances will also be destroyed .
When using the kep- alive When the function , Add the following two cycles .

activated stay keep- alive Called when the component is activated ;
deactivated stay keep-live Called when the component is disabled .
Vue2.5.0 A cycle hook has been added to the version :ErrorCaptured, Called when an error is caught from a descendant component .
5、 Please elaborate on your understanding of Vue.js Life cycle understanding .

The total is divided into 8 Stages , Respectively beforeCreate、created、beforeMount、 mounted、beforeUpdate、 updated、 beforeDestroyed、 destroyed.

beforeCreate: After the instance is initialized , Data observer ( data observer) and event/ watcher Call before event configuration .
created: Call... Immediately after the instance is created . In this step , The instance has completed the following configuration : Data observer , Operations on properties and methods , watch/event Event callback . However , The mount phase has not yet begun ,$el Properties are not currently visible .
beforeMount: It is called before the mount begins , dependent render Function first call .
mounted:    el Newly created vm.$el Replace , And after mounting to the instance, call the hook if root Instance mounts a document element , When calling mounted when vm.sel Also in the document .
beforeUpdate: Called when data is updated , It happened in the virtual world DOM Before re rendering and patching .
updated: Virtual due to data changes DOM Re rendering and patching , The hook is called after that .
beforeDestroy: Call before instance destruction . In this step , Instance is still fully available .
destroyed: stay Vue. js Call after instance destruction . After calling ,Vue. js Everything indicated by the instance is unbound , All event listeners will be removed , All child instances will also be destroyed .
When using the kep- alive When the function , Add the following two cycles .

activated stay keep- alive Called when the component is activated ;
deactivated stay keep-live Called when the component is disabled .
Vue2.5.0 A cycle hook has been added to the version :ErrorCaptured, Called when an error is caught from a descendant component .

6、 Please describe the encapsulation Vue Function process of components .

Components can improve the development efficiency of the whole project , Be able to abstract pages into several relatively independent modules , It solves the problem of low efficiency in traditional project development 、 Difficult to maintain 、 Reusability and so on .

Use Vue.extend Method to create a component , Use Vue.component Method registration component . Data required for subcomponent , Can be in props Data received in . After the sub component modifies the data , If you want to pass data to the parent component , May adopt emit Method .

7、 How do you know each other vuex Of ?

vuex It can be understood as a development mode or framework . It's right Vue. js Extension of framework data level . Passing state ( data source ) Centralized management of driver changes . The state of the application is focused on store in . The way to change the status is to submit mutations, This is a synchronous transaction . Asynchronous logic should be encapsulated in action in .

8、Vue- loader What is it? ? What are its uses ?

It's parsing .vue A loader for files , Can be template/js/style convert to JavaScript modular .

The purpose is through vue-loader, JavaScript Can write EMAScript 6 grammar , style Styles can be applied scss or less, template You can add jade Grammar, etc .

9、 Please say vue.cli Project src Usage of each folder and file in the directory .

assets A folder holds static resources ;components Storing components ;router Define routing related configuration ;view It's the view ;app. vue Is an application main component ;main.js It's the entry file .

10、 stay Vue.cli How to use custom components in ? What problems have you encountered in the process of using ?

The specific steps are as follows .

(1) stay components Create a new component file in the directory , Scripts must export exposed interfaces .

(2) Import the required pages ( Components ).

(3) Inject imported components into uejs Of the components Properties of the .

(4) stay template Using custom components in view of .

11、 Talk to you about vue.js Of template Understanding of compilation .

In short , It's the first thing to turn it into AST( Abstract Syntax Tree, Abstract syntax tree ), The syntax structure of source code is abstracted into tree representation , And then through render Function to render , And back to VNode( Vue. js The virtual DOM node ).

The detailed steps are as follows .

(1) adopt compile The compiler the template Translate it into AST, compile yes create Compiler The return value of , createCompiler Used to create compilers . in addition , compile Also responsible for consolidation option.

(2)AST Pass by generate( take AST Turn it into render funtion String procedure ) obtain render function , render The return value of VNode, VNode yes Vue.Js The virtual DOM node , There is a child node with a tag name 、 Text etc. .

12、 How to make CSS Works only in the current component ?

In every one of them Vue.js Each component can define its own CSS、 JavaScript Code . If you want what's written in the component CSS Works only on the current component , Only need Style add Scoped attribute , namely <style scoped></style>.
13、 How to detect data changes ?

because JavaScript Limitations of features , Vue. js The following array changes cannot be detected , That is, the changed data in the following array “ The loss of ” 了 .

Set elements by direct index , Such as app.arr[0]=...

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

To solve this problem ,Vue.js Extended observation array , Added a $set( ) Method , Array modified by this method , Can trigger view update , Detect data changes .

app.$set(app. arr, 5, 500);
14、 How to detect object changes ?

because JavaScript Limitations of features ,Vue.js Cannot detect addition or deletion of object properties . because Vue.js Convert properties to getter/setter, So the property must be in the data Object definition , To make the Vue.js Transform it and make it respond , 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' and 'data.obj.a' Now it's responsive

app. obj. b=2

//'app.obj.b' Not responsive

data.obj.b=2

//data.obj.b' Not responsive
If you need to add properties after the instance is created and make it responsive , have access to $set Example method .

app.$set(app.obj,'b',500)

// 'app.obj.b' and 'data.obj.b' Now it's responsive
For normal data objects , You can use the global approach Vue.set( object,key, value).

Vue.set(data.obj,"b',500)
//'app.obj.b' and 'cata,obj.b' Now it's responsive
15、 The way Vue.js The page flashes {{message}}.

Vue. js Provides a v- cloak Instructions , The instruction remains on the element all the time , Until the associated instance finishes compiling . When and CSS When used together , This directive can hide uncompiled tags , Until the end of instance compilation . Usage is as follows .

[v-cloak ]{

 display:none;

}

<div v-cloak> { { title } }</div>
such <div> Will not show , Until the end of compilation .
16、 How to solve the problem of too deep data hierarchy ?

In business development , There are often asynchronous access to data , Sometimes the data level is deep , As the following code .

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

have access to vm.$set Define a layer of data manually .

vm.$set ("demo",a .b.c.d)
17、 Vue3.x Principle of responsive data
Vue3.x change to the use of sth. Proxy replace Object.defineProperty.
because Proxy It can directly monitor the changes of objects and arrays , And there are as many as 13 Interception methods . And as a new standard, it will be continuously optimized by browser manufacturers .
Proxy Only the first layer of the object will be represented ,Vue3 How to deal with this problem ?
Judge the present Reflect.get Whether the return value of is Object, If so, then pass reactive How to act as an agent , In this way, the depth observation is realized .
Monitoring arrays can trigger multiple times get/set, So how to prevent triggering multiple times ? We can judge key Is the current proxy object target Self attribute , You can also judge whether the old value is equal to the new value , Only one of the above two conditions , It's possible to carry out trigger.

18、Vue3.0 Why use it in the library Proxy API replace defineProperty API?
1.defineProperty API The biggest limitation of this method is that it can only monitor singleton properties .
Vue2.x The responsive implementation in is based on defineProperty Medium descriptor, Yes data The properties in are traversed + recursive , Set for each property getter、setter. That's why Vue Only right data The reason for responding to the properties predefined in .
2.Proxy API The monitor of is aimed at an object , Then all operations on this object will enter the listening operation , This makes it possible to proxy all properties , Will bring a lot of performance improvement and better code .
Proxy Can be interpreted as , Set up a layer in front of the target object “ Intercept ”, External access to the object , All must be intercepted through this layer first , So it provides a mechanism , It can filter and rewrite external access .
3. Responsive is inert .
stay Vue.js 2.x in , For an object with deep nested properties , We need to hijack the deep changes inside it , You need to recursively traverse this object , perform Object.defineProperty Make every layer of object data responsive , There is no doubt that there will be a lot of performance consumption .
stay Vue.js 3.0 in , Use Proxy API It can't monitor the deep-seated property changes inside the object , So the way it's handled is in the getter The recursive response form in the middle , The advantage of this is that the internal properties that are actually accessed will become responsive , Simply speaking, it can be said to be responsive on demand , Reduce performance consumption .
19、Proxy And Object.defineProperty Comparison of advantages and disadvantages
1.Proxy You can listen directly to objects rather than properties ;
2.Proxy Can directly monitor the changes in the array ;
3.Proxy There are as many as 13 Interception methods , Not limited to, apply、ownKeys、deleteProperty、has Wait a minute yes Object.defineProperty Do not have the ;
4.Proxy Returns a new object , We can only manipulate new objects to achieve the goal , and Object.defineProperty You can only traverse the object properties and modify them directly ;
5.Proxy As a new standard, it will be continuously optimized by browser manufacturers , That is, the legendary performance bonus of the new standard ;
6.Object.defineProperty The advantages are as follows :
Compatibility is good. , Support IE9, and Proxy There are browser compatibility issues with , And it doesn't work polyfill Grinding , therefore Vue The author of the claim that we need to wait until the next major version ( 3.0 ) Ability to use Proxy rewrite .

vue Of the components in data Why is it a function ? and new Vue In the example ,data Can be an object directly
We know ,Vue The component is actually a Vue example .

JS Instances in are created through constructors , Each constructor can new There are many examples , Then each instance inherits the method or property on the prototype .

Vue Of data The data is actually Vue Properties on prototypes , The data is in memory .Vue To ensure that the data Independence of data , The function must be used , Not the object .

Because if you use objects , Each instance ( Components ) The use of data The data are interactive , Of course, that's not what we want . Object is a reference to a memory address , If you define an object directly, it will be used between components , This will cause data interaction between components .

After using function , It uses data() function ,data() Function this It points to the current instance itself , It won't affect each other .

and new Vue Example , It will not be reused , So there is no problem of referencing objects .
20. The differences and advantages and disadvantages of single page application and multi page application
answer : Single page application (SPA), In a popular sense, it means that there is only one main page application , The browser starts loading all the necessary html, js, css. All page content is contained in this so-called main page . But at the time of writing , Still write separately ( Page fragment ), Then it is dynamically loaded by the router during the interaction , Single page page Jump , Refresh only local resources . Most of them are used in pc End .

Multi page (MPA), It means that there are multiple pages in an application , When the page jumps, the whole page is refreshed

Advantages of a single page : Good user experience , fast , Content changes do not need to reload the entire page , Based on this spa Less pressure on the server ; Fore and aft end separation ; Page effect will be more cool ( For example, when switching page content, special animation ).

Disadvantages of single page : It's not good for seo; Navigation not available , If you have to navigate, you need to move forward by yourself 、 back off .( Because it's a single page, you can't use the browser's forward and backward functions , So you need to build your own stack management ); It takes a lot of time to load for the first time ; The complexity of the page is much higher .

版权声明
本文为[qqcc]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/06/20210603043624176c.html

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless