Glory gold
1. What are the advantages of Vue? The disadvantages of Vue?
Advantages: progressive, componentized, lightweight, virtual dom, responsive, single page routing, separation of data and view
Disadvantages: single page is not conducive to seo, does not support IE8 or below, and takes a long time to load the first screen
2. Why is Vue a progressive framework?
Progressive: Generally speaking, you can use whatever you want. We don't force you. If you want to use component, you can use it without using it. If you want to use vuex, you can use it without using it
3. What are the similarities and differences between Vue and React?
Similarities:
- 1. All use virtual dom
- 2. Component development
- 3. Both are one-way data flows (between parent and child components, it is not recommended to modify the data passed down from the parent)
- 4. Both support server-side rendering
difference:
- 1. JSX of react and template of Vue
- 2. Data change, React manual (setState), Vue automatic (initialization, responsive processing, Object.defineProperty)
- 3.React one-way binding and Vue two-way binding
- 4. Redux of react and Vuex of Vue
4. What is MVVM? What's the difference between and MVC?
MVC
- Model: responsible for fetching data from the database
- View: the place responsible for displaying data
- Controller: where users interact, such as click events, etc
- Idea: the Controller displays the data of the Model on the View
MVVM
- VM: that is, view model does two things to achieve two-way binding of data. One is to convert the [model] into [view], that is, the data transmitted from the back end into the page you see. The implementation method is: data binding. The second is to convert view into model, that is, the page you see into back-end data. The implementation method is: DOM event listening.
- Idea: it realizes the automatic synchronization between View and Model, that is, when the attributes of Model are changed, we no longer need to manually operate Dom elements to change the display of View, but the display of View layer corresponding to the attribute will change automatically after changing the attribute (corresponding to Vue data-driven idea)
difference
On the whole, MVVM is much simpler than MVC. It not only simplifies the dependence on business and interface, but also solves the problem of frequent data updates. There is no need to operate DOM elements with selectors. Because in MVVM, the View does not know the existence of the Model, and the Model and ViewModel do not observe the View, this low coupling mode improves the reusability of the code
Is Vue an MVVM framework?
Vue is an MVVM framework, but it does not strictly comply with MVVM, because MVVM stipulates that Model and View cannot communicate directly, and Vue's ref can do this
5. What is the difference between Vue and JQuery? Why give up JQuery and use Vue?
- 1.jQuery operates DOM directly, Vue does not operate DOM directly, Vue's data and view are separated, and Vue only needs to operate data
- 2.jQuery operates DOM frequently, and Vue uses virtual DOM technology to greatly improve the performance when updating dom
- 3.Vue does not advocate direct operation of DOM, and developers only need to focus most of their energy on the data level
- 4. Some libraries integrated by Vue greatly improve development efficiency, such as Vuex, Router, etc
6. Who is the author of Vue? Say its name out loud!!!
His name is squid West
Eternal diamond
7. Why is data a function and returns an object?
The reason why data is only one function is that a component may call multiple times, and each call will execute the data function and return a new data object. In this way, data pollution between multiple calls can be avoided.
8. Which Vue modifiers have been used?
You can read my article "Invincible" 13 Vue modifiers that interviewers like to ask
9. What Vue internal instructions have been used?
10. What are the value transfer methods between components?
- The parent component passes the value to the child component, and the child component receives it using props
- The child component passes the value to the parent component, and the child component uses the $emit + event to pass the value to the parent component
- In the component, you can use $parent and $children to obtain parent component instances and child component instances, and then obtain data
- Using $attrs and $listeners, it is convenient to transfer values when re encapsulating some components, such as a - > b - > C
- Use $refs to get the component instance, and then get the data
- Using Vuex for status management
- Use eventBus to trigger events across components, and then transfer data
- Using provide and inject, we are officially advised not to use this. I found a lot of use when looking at the ElementUI source code
- Use the browser to cache locally, such as localStorage
11. What are the routing modes? What's the difference?
- hash mode: trigger the hashchange event by changing the content behind the # number to realize route switching
- history mode: switch URLs through pushState and replaceState to trigger the pop state event and realize route switching. Back end cooperation is required
12. How to set dynamic class and dynamic style?
- Dynamic class object: < div: class = "{'is active': true, 'Red': isred}" > < / div >
- Dynamic class array: < div: class = "['Is active ', isred?' Red ':' ']" > < / div >
- Dynamic style object: < div: style = "{color: textcolor, fontsize: '18px'}" > < / div >
- Dynamic style array: < div: style = "[{color: textcolor, fontsize: '18px'}, {FontWeight: '300'}]" > < / div >
13. What is the difference between V-IF and v-show?
- 1.v-if realizes explicit and implicit by controlling the deletion and generation of dom elements. Each explicit and implicit will make the component run through the life cycle again, because explicit and implicit determines the generation and destruction of components
- 2.v-show controls the css style of dom elements to realize explicit and implicit, and will not be destroyed
- 3. Use v-show frequently or in large quantities, otherwise use v-if
14. What is the difference between computed and watch?
- 1.computed relies on existing variables to calculate a target variable. In most cases, multiple variables are put together to calculate a variable, and computed has a cache mechanism. When the dependency value remains unchanged, it will directly read the cache for reuse, and computed cannot perform asynchronous operation
- 2.watch monitors the change of a variable and executes the corresponding callback function. Usually, the change of a variable determines the change of multiple variables. watch can perform asynchronous operation
- 3. Keep it simple: in general, computed is many to one and watch is one to many
15. Vue's life cycle, talk about it?
16. Why are v-if and v-for not recommended to use the same label?
In Vue2, the priority of v-for is higher than that of v-if. Let's take an example
<div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item !== 3"> {{item}} </div> Copy code
The above method is that v-for and v-if exist at the same time. We will traverse all seven elements first, then judge whether they are 3 and hide them. The disadvantage is that useless 3 nodes are rendered and useless dom operations are added. It is recommended to use computed to solve this problem:
<div v-for="item in list"> {{item}} </div> computed() { list() { return [1, 2, 3, 4, 5, 6, 7].filter(item => item !== 3) } } Copy code
17. What are the attributes of vuex? What's the use?
- State: defines the data structure of the application state. You can set the default initial state here.
- getter: allows components to obtain data from the store. The mapGetters auxiliary function only maps getters in the store to local calculation properties.
- Mutation: is the only way to change the state in the store and must be a synchronization function.
- Action: used to submit a mutation instead of directly changing the state. It can contain any asynchronous operation.
- Module: allows you to split a single store into multiple stores and save them in a single state tree at the same time.
Supreme star shine
18. What should I do with data that does not require responsiveness?
In our Vue development, there will be some data that have not been changed from beginning to end. Since this dead data does not change, it does not need to be processed responsively. Otherwise, it will only do some useless work consumption performance, such as some write dead drop-down boxes, write dead grid data, and these dead data with a large amount of data. If they are processed responsively, That consumes a lot of performance.
// Method 1: define data outside data data () { this.list1 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } this.list2 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } this.list3 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } this.list4 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } this.list5 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } return {} } // Method 2: object freeze() data () { return { list1: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list2: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list3: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list4: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list5: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), } } Copy code
19. What are the attributes of watch and what are their uses?
When we listen to a basic data type:
watch: { value () { // do something } } Copy code
When we listen for a reference data type:
watch: { obj: { handler () { // Execute callback // do something }, deep: true, // Whether to conduct in-depth monitoring immediate: true // Whether to initially execute the handler function } } Copy code
20. Parent child component life cycle sequence
Parent beforecreate - > parent created - > parent beforemount - > child beforecreate - > child created - > child beforemount - > child mounted - > parent mounted
21. The view cannot be updated when the new attribute of the object is deleted, and the view cannot be updated when the attribute is deleted. Why? What should I do?
- Reason: object Defineproperty does not hijack the new property of the object
- Object new properties cannot update view: use Vue$ Set (obj, key, value), this$ set(obj, key, value)
- Deleting properties cannot update the view: use Vue$ Delete (obj, key), this$ delete(obj, key)
22. What if arr[index] = xxx cannot update the view directly? Why? What should I do?
- Reason: Vue did not object the array The property of defineproperty is hijacked, so the view cannot be updated directly with arr[index] = xxx
- Use the slice method of the array, arr.slice (index, 1, item)
- Using Vue$ set(arr, index, value)
23. Custom instructions
I suggest reading this article 8 very practical Vue custom instructions
24. Use and principle of slot?
I suggest reading this article "Vue source code learning" do you really know how Slot slot is "inserted"
25. Why not use index as key and random number as key?
for instance:
<div v-for="(item, index) in list" :key="index">{{item.name}}</div> list: [ { name: 'Xiao Ming', id: '123' }, { name: 'Xiao Hong', id: '124' }, { name: 'floret', id: '125' } ] Render as <div key="0">Xiao Ming</div> <div key="1">Xiao Hong</div> <div key="2">floret</div> Now I execute list.unshift({ name: 'Kobayashi', id: '122' }) Render as <div key="0">Kobayashi</div> <div key="1">Xiao Ming</div> <div key="2">Xiao Hong</div> <div key="3">floret</div> Comparison between old and new <div key="0">Xiao Ming</div> <div key="0">Kobayashi</div> <div key="1">Xiao Hong</div> <div key="1">Xiao Ming</div> <div key="2">floret</div> <div key="2">Xiao Hong</div> <div key="3">floret</div> It can be seen that if you use index do key In fact, the original three items are updated and florets are added. Although the rendering purpose is achieved, the performance is lost Now we use id Do it key,Render as <div key="123">Xiao Ming</div> <div key="124">Xiao Hong</div> <div key="125">floret</div> Now I execute list.unshift({ name: 'Kobayashi', id: '122' }),Render as <div key="122">Kobayashi</div> <div key="123">Xiao Ming</div> <div key="124">Xiao Hong</div> <div key="125">floret</div> Comparison between old and new <div key="122">Kobayashi</div> <div key="123">Xiao Ming</div> <div key="123">Xiao Ming</div> <div key="124">Xiao Hong</div> <div key="124">Xiao Hong</div> <div key="125">floret</div> <div key="125">floret</div> It can be seen that the original three items remain unchanged, but Kobayashi is added, which is the most ideal result Copy code
Using index is the same as using random numbers. Random numbers change every time. They are not specific. They are very scum men and consume performance. Therefore, refuse scum men and choose honest people
26. What's the use of nextTick?
For example, in vue:
this.name = 'Lin Sanxin' this.age = 18 this.gender = 'male' Copy code
We modified three variables. The question arises. Is the DOM updated every time we modify it? No, Vue adopts the asynchronous update strategy. Generally speaking, if you modify multiple times in the same event loop, you will update the view once in a unified way, so as to save performance
If you understand the above, you should also understand the following examples:
<div ref="testDiv">{{name}}</div> name: 'Kobayashi' this.name = 'Lin Sanxin' console.log(this.$refs.testDiv.innerHTML) // What's here Copy code
The answer is "Kobayashi". As mentioned earlier, Vue updates asynchronously, so once the data is updated, the view has not been updated, so what do you want to do to get the latest view data?
this.name = 'Lin Sanxin' this.$nextTick(() => { console.log(this.$refs.testDiv.innerHTML) // Lin Sanxin }) Copy code
27. What is Vue's SSR? What are the benefits?
- SSR is server-side rendering
- Developed based on nodejs serve service environment, all html codes are rendered on the server
- The data is returned to the front end, and then the front end is "activated", which can become the html code recognized by the browser
- SSR loads faster for the first time, has better user experience and better seo optimization, because the crawler can see the content of the whole page. If it is a Vue project, the data needs to be parsed, so the crawler will not wait for your data to be loaded. In fact, the seo experience of Vue project is not very good
The strongest King
28. How is Vue responsive implemented?
The overall idea is data hijacking + observer mode
Inside the object, use the defineReactive method to use object Defineproperty hijacks properties (only existing properties will be hijacked), and arrays are implemented by overriding array methods. When the page uses corresponding attributes, each attribute has its own dep attribute to store the watcher it depends on (dependency Collection). When the attribute changes, it will notify its corresponding watcher to update (distribute updates).
To learn more about the process, I suggest reading my Vue source code analysis series
const { arrayMethods } = require('./array') class Observer { constructor(value) { Object.defineProperty(value, '__ob__', { value: this, enumerable: false, writable: true, configurable: true }) if(Array.isArray(value)) { value.__proto__ = arrayMethods this.observeArray(value) } else { this.walk(value) } } walk(data) { let keys = Object.keys(data) for(let i = 0; i < keys.length; i++) { const key = keys[i] const value = data[key] defineReactive(data, key, value) } } observeArray(items) { for(let i = 0; i < items.length; i++) { observe(items[i]) } } } function defineReactive(data, key, value) { const childOb = observe(value) const dep = new Dep() Object.defineProperty(data, key, { get() { console.log('Get value') if (Dep.target) { dep.depend() if (childOb) { childOb.dep.depend() if (Array.isArray(value)) { dependArray(value) } } } return value }, set(newVal) { if (newVal === value) return observe(newVal) value = newVal dep.notify() } }) } function observe(value) { if (Object.prototype.toString.call(value) === '[object Object]' || Array.isArray(value)) { return new Observer(value) } } function dependArray(value) { for(let e, i = 0, l = value.length; i < l; i++) { e = value[i] e && e.__ob__ && e.__ob__.dep.depend() if (Array.isArray(e)) { dependArray(e) } } } // array.js const arrayProto = Array.prototype const arrayMethods = Object.create(arrayProto) const methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'reverse', 'sort' ] methodsToPatch.forEach(method => { arrayMethods[method] = function (...args) { const result = arrayProto[method].apply(this, args) const ob = this.__ob__ var inserted switch (method) { case 'push': case 'unshift': inserted = args break; case 'splice': inserted = args.slice(2) default: break; } if (inserted) ob.observeArray(inserted) ob.dep.notify() return result } }) Copy code
29. Why only hijack objects and override arrays?
Because there are at most dozens of attributes of an object, the number of interceptions is small, but the array may have hundreds and thousands of items, which is very performance-consuming. Therefore, directly rewriting the method on the array prototype is a performance-saving scheme
30. Vue's template compilation principle?
Because this question may be long, so:
I suggest you read this article "Vue source code learning (II)" what you don't know - the principle of template compilation
31. Vue's principle of computed and watch?
Because this question may be long, so:
I suggest you read this article "Vue source code learning (IV)" determined to write a calculated, watch principle that everyone can understand
32. Vue. Principle of set method?
function set(target, key, val) { // Determine whether it is an array if (Array.isArray(target)) { // Judge who is big and who is small target.length = Math.max(target.length, key) // Execute splice target.splice(key, 1, val) return val } const ob = target.__ob__ // If this object is not a responsive object, set it directly and return it if (key in target && !(key in target.prototype) || !ob) { target[key] = val return val } // Otherwise, add a new attribute and handle it responsively defineReactive(target, key, val) return val } Copy code
33. Vue. How does the delete method work?
function del (target, key) { // Determine whether it is an array if (Array.isArray(target)) { // Execute splice target.splice(key, 1) return } const ob = target.__ob__ // The object itself does not have this property and returns directly if (!(key in target)) return // Otherwise, delete this property delete target[key] // Judge whether it is a responsive object. If not, return it directly if (!ob) return // If yes, notify the view update after deletion ob.dep.notify() } Copy code
34. How does nexttick work?
let callbacks = []; //Callback function let pending = false; function flushCallbacks() { pending = false; //Restore flag to false // Execute callbacks in turn for (let i = 0; i < callbacks.length; i++) { callbacks[i](); } } let timerFunc; //Firstly, the asynchronous refresh is realized by using micro tasks and graceful degradation of priority if (typeof Promise !== "undefined") { // If promise is supported const p = Promise.resolve(); timerFunc = () => { p.then(flushCallbacks); }; } else if (typeof MutationObserver !== "undefined") { // MutationObserver is mainly used to listen for dom changes. It is also an asynchronous method let counter = 1; const observer = new MutationObserver(flushCallbacks); const textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true, }); timerFunc = () => { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else if (typeof setImmediate !== "undefined") { // If the previous judgment is not supported, setImmediate timerFunc = () => { setImmediate(flushCallbacks); }; } else { // Finally, setTimeout is adopted for demotion timerFunc = () => { setTimeout(flushCallbacks, 0); }; } export function nextTick(cb) { callbacks.push(cb); if (!pending) { pending = true; timerFunc(); } } Copy code
35. What's the use of key? Talk about diff algorithm?
Read this article directly: Why not use index as a key in Vue? (detailed explanation of diff algorithm)
I'm not as good as him
Unpopular knowledge points
36. What happens if a sub component changes the data in props
- The changed props data is the basic type
If the basic type is modified, an error will be reported
props: { num: Number, } created() { this.num = 999 } Copy code
- The changed props data is a reference type
props: { item: { default: () => {}, } } created() { // No error is reported, and the parent data will change accordingly this.item.name = 'sanxin'; // An error will be reported, which is the same as that of the basic type this.item = 'sss' }, Copy code
37. How does props customize validation
props: { num: { default: 1, validator: function (value) { // If the return value is true, the verification fails and an error is reported return [ 1, 2, 3, 4, 5 ].indexOf(value) !== -1 } } } Copy code
38. What is the use of the immediate attribute of watch?
For example, you need to request data once when you create, and when the search value changes, you also need to request data. We will write this:
created(){ this.getList() }, watch: { searchInputValue(){ this.getList() } } Copy code
You can write this using immediate. When it is true, it will be executed initially
watch: { searchInputValue:{ handler: 'getList', immediate: true } } Copy code
39. How to exclude the listening of some attributes when watch listens to an object
The following code is to re request data when params changes, whether a, b, c or d attributes change
data() { return { params: { a: 1, b: 2, c: 3, d: 4 }, }; }, watch: { params: { deep: true, handler() { this.getList; }, }, } Copy code
But what if I just want to re request when a and b change and not re request when c and d change?
mounted() { Object.keys(this.params) .filter((_) => !["c", "d"].includes(_)) // Exclude listening to c and d attributes .forEach((_) => { this.$watch((vm) => vm.params[_], handler, { deep: true, }); }); }, data() { return { params: { a: 1, b: 2, c: 3, d: 4 }, }; }, watch: { params: { deep: true, handler() { this.getList; }, }, } Copy code
40. data-v-xxxxx is found when reviewing the element. What is this?
This is generated by using the scoped tag when marking css in vue files. To ensure that css in each file does not affect each other, each component is uniquely marked. Therefore, a new 'data-v-xxx' tag will appear every time a component is introduced
41. How does computed implement parameter transfer?
// html <div>{{ total(3) }} // js computed: { total() { return function(n) { return n * this.num } }, } Copy code
42. Use of Vue's hook
- Used in the same component
This is the way we often use timers
export default{ data(){ timer:null }, mounted(){ this.timer = setInterval(()=>{ //Specific implementation contents console.log('1'); },1000); } beforeDestory(){ clearInterval(this.timer); this.timer = null; } } Copy code
The bad thing about the above method is that you have to define a timer variable globally. You can use hook to do this:
export default{ methods:{ fn(){ const timer = setInterval(()=>{ //Specific execution code console.log('1'); },1000); this.$once('hook:beforeDestroy',()=>{ clearInterval(timer); timer = null; }) } } } Copy code
- 7.2 use of parent-child components
If the child component needs to trigger a function of the parent component when mounted, it will be written as follows:
//Parent component <rl-child @childMounted="childMountedHandle" /> method () { childMountedHandle() { // do something... } }, // Subcomponents mounted () { this.$emit('childMounted') }, Copy code
It is more convenient to use hook:
//Parent component <rl-child @hook:mounted="childMountedHandle" /> method () { childMountedHandle() { // do something... } }, Copy code
43. Are provide and inject responsive?
// Ancestor component provide(){ return { // Keyname: {Name: this. Name}, / / value is an object to implement a response, that is, a reference type keyName: this.changeValue // You can also use the function [note that the function here is regarded as value instead of this.changeValue()] // keyName: 'test' value if it is a basic type, the response type cannot be implemented } }, data(){ return { name:'Zhang San' } }, methods: { changeValue(){ this.name = 'Changed name-Li Si' } } // Descendant component inject:['keyName'] create(){ console.log(this.keyName) // Changed name - Li Si } Copy code
44.Vue's el attribute and $mount priority?
For example, in the following case, which node will Vue render to
new Vue({ router, store, el: '#app', render: h => h(App) }).$mount('#ggg') Copy code
This is an official figure. It can be seen that when el and $mount exist at the same time, El priority > $mount
45. Have dynamic instructions and parameters been used?
<template> ... <aButton @[someEvent]="handleSomeEvent()" :[someProps]="1000" />... </template> <script> ... data(){ return{ ... someEvent: someCondition ? "click" : "dbclick", someProps: someCondition ? "num" : "price" } }, methods: { handleSomeEvent(){ // handle some event } } </script> Copy code
46. How to re render the same routing components?
Developers often encounter situations where multiple routes resolve to the same Vue component. The problem is that Vue, for performance reasons, shared components will not be re rendered by default. If you try to switch between routes using the same components, nothing will change.
const routes = [ { path: "/a", component: MyComponent }, { path: "/b", component: MyComponent }, ]; Copy code
What if you still want to re render? You can use key
<template> <router-view :key="$route.path"></router-view> </template> Copy code
47. Custom v-model
By default, v-model is the syntax sugar on the @ input event listener and the: value attribute. However, you can specify a model attribute in your Vue component to define what event and value attributes to use - great!
export default: { model: { event: 'change', prop: 'checked' } } Copy code
48. How to get the initial state of a data in data?
In development, it is sometimes necessary to calculate the initial state. for example
data() { return { num: 10 }, mounted() { this.num = 1000 }, methods: { howMuch() { // Calculate how much num has increased, that is, 1000 - the initial value // You can use this$ options. data(). XXX to get the initial value console.log(1000 - this.$options.data().num) } } Copy code
49. Why not suggest that v-for and v-if exist at the same time
<div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item !== 3"> {{item}} </div> Copy code
The above method is that v-for and v-if exist at the same time. We will traverse all seven elements first, then judge whether they are 3 and hide them. The disadvantage is that useless 3 nodes are rendered and useless dom operations are added. It is recommended to use computed to solve this problem:
<div v-for="item in list"> {{item}} </div> computed() { list() { return [1, 2, 3, 4, 5, 6, 7].filter(item => item !== 3) } } Copy code
50. When calculating variables, which is better, methods or calculated?
<div> <div>{{howMuch1()}}</div> <div>{{howMuch2()}}</div> <div>{{index}}</div> </div> data: () { return { index: 0 } } methods: { howMuch1() { return this.num + this.price } } computed() { howMuch2() { return this.num + this.price } } Copy code
Computed is better because it has a cache. For example, if the index changes from 0 to 1, the view update will be triggered. At this time, the methods will be executed again, but computed will not, because the two variables num and price that computed depends on remain unchanged.
Author: Sunshine_Lin
Link: https://juejin.cn/post/6984210440276410399
Source: Nuggets
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.