The glory of gold

1. Advantages of Vue? Vue’s weakness?

Benefits: Progressive, componentized, lightweight, virtual DOM, responsive, single-page routing, data and view separation

Disadvantages: Single page is not conducive to SEO, does not support Internet Explorer 8 or lower, and takes a long time to load on the first screen

2. Why is Vue an incremental framework?

Progressive: popular point is, you want to use what you use, we do not force you. You can use Component if you want, you can use vuex if you want, you can use vuex if you don’t want

What are the similarities and differences between Vue and React?

Similarities:

  • 1. Both use the virtual DOM
  • 2. Componentized development
  • 3. One-way data flows (between parent and child components, it is not recommended that the child modify the data transmitted from the parent)
  • 4. Both support server rendering

Difference:

  • React JSX, Vue template
  • 2. Data changes, React manually (setState), Vue automatically (initialize reactive processing, Object.defineProperty)
  • React Unidirectional binding and Vue bidirectional binding
  • React Redux, Vue Vuex

4. What is MVVM? How is it different from MVC?

MVC

  • Model: Is responsible for fetching data from the database
  • View: The place responsible for displaying data
  • Controller: A place where users interact, such as click events, etc
  • Idea: The Controller displays the Model’s data on the View

MVVM

  • VM, or View-Model, does two things to achieve bidirectional binding of data. One is to convert the [Model] into the [View], which is to convert the data passed from the back end into the page you see. This is done by data binding. The second is to transform [view] into [model], that is, to see the page into back-end data. This is done by DOM event listening.
  • Idea: Automatic synchronization of View and Model is realized, that is, when the attributes of Model change, we no longer need to manually manipulate Dom elements to change the display of View, but after changing the attributes, the corresponding View layer display will automatically change (corresponding to Vue data-driven idea).

The difference between

Overall, MVVM is much simpler than MVC. It not only simplifies business and interface dependencies, but also solves the problem of frequent data updates, eliminating the need to manipulate DOM elements with selectors. Because in MVVM, the View is unaware of the Existence of the Model, and the Model and ViewModel cannot observe the View, this low-coupling pattern improves code reusability

Is Vue the MVVM framework?

Vue is an MVVM framework, but it is not strictly MVVM compliant because MVVM dictates that the Model and View cannot communicate directly, whereas Vue’s ref does

5. What is the difference between Vue and JQuery? Why did you leave JQuery for Vue?

  • 1. JQuery directly operates on the DOM, Vue does not directly operate on the DOM, Vue data and view are separate, Vue only needs to operate on data
  • 2. In the scene of frequent DOM manipulation, jQuery frequently manipulates DOM, while Vue makes use of virtual DOM technology to greatly improve the performance of DOM update
  • 3. Direct manipulation of the DOM is not advocated in Vue, and developers only need to focus most of their efforts on the data side
  • 4. Some libraries integrated with Vue, such as Vuex, Router, etc., greatly improve the development efficiency

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?

Data is a function because a component may be called multiple times, and each call executes the data function and returns a new data object, thus avoiding data contamination between multiple calls.

8. What Vue modifiers have you used?

Check out my article on the 13 favorite Vue modifiers interviewers ask about

9. What internal Vue directives have you used?

10. What are the ways of transferring values between components?

  • The parent component passes a value to the child component, which uses itpropsTo receive
  • The child component passes values to the parent component, which the child component uses$emit + eventPass values to the parent component
  • Component can be used in$parentand$childrenGet the parent and child component instances, and then get the data
  • use$attrsand$listenersIn the secondary encapsulation of some components, such as A->B->C, values can be easily transmitted
  • use$refsGet the component instance, which in turn gets the data
  • useVuexState Management
  • useeventBusCross component trigger events that pass data
  • useprovideandinjectWe’re officially advised not to use this. I’m reading itElementUISource code found when a lot of use
  • Use browser local caching, for examplelocalStorage

11. What are the routing modes? What’s the difference?

  • Hash mode: Pass# no.Subsequent content changes to triggerhashchangeEvent to implement route switchover
  • History mode: YespushStateandreplaceStateSwitching urls and switching routes requires the cooperation of the back end

12. How to set dynamic class, dynamic style?

  • Dynamic class objects:<div :class="{ 'is-active': true, 'red': isRed }"></div>
  • Dynamic class array:<div :class="['is-active', isRed ? 'red' : '' ]"></div>
  • Dynamic style objects:<div :style="{ color: textColor, fontSize: '18px' }"></div>
  • Dynamic style array:<div :style="[{ color: textColor, fontSize: '18px' }, { fontWeight: '300' }]"></div>

13. What’s the difference between V-IF and V-show?

  • 1.v-ifExplicit hiding is achieved by controlling the deletion and generation of DOM elements, each explicit hiding causing the component to run through the lifecycle again because explicit hiding determines the generation and destruction of the component
  • 2.v-showExplicit implicit is implemented by controlling THE CSS style of DOM elements without destruction
  • 3. Frequent or large amount of explicit and implicit usev-show, otherwise usev-if

What is the difference between computed and Watch?

  • 1.computedIn most cases, a target variable is computed based on an existing variableMultiple variablesLet’s put it all togetherA variableAnd,computedwithCaching mechanisms, it will directly read the cache for reuse if the dependency value remains unchanged.computedCannot beAsynchronous operations
  • 2.watchListen for a change in a variable and execute the corresponding callback function, usuallyA variableIs determined byMultiple variablesThe change,watchCan be doneAsynchronous operations
  • 3. Simply remember: under normal circumstancescomputedisFor one more.watchisMore than a pair of

15. What is the life cycle of Vue?

16. Why are v-if and V-for not recommended for the same label?

In Vue2, v-for has a higher priority than V-if. Let’s take an example

<div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item ! {{item}} </div> Copy codeCopy the code

If v-for and V-if exist at the same time, it traverses all 7 elements first, then determines whether they are 3 one by one and hides the 3. The disadvantage of this is that it renders useless 3 nodes and increases useless DOM operations. It is recommended to solve this problem using computed data:

<div v-for="item in list"> {{item}} </div> computed() { list() { return [1, 2, 3, 4, 5, 6, 7].filter(item => item ! == 3)}} Copy the codeCopy the code

17. What are the attributes of vuex? For what?

  • State: Data structure that defines the State of the application, where the default initial State can be set.
  • Getter: Allows the component to get data from the Store. The mapGetters helper function simply maps the getters in the Store to local computed properties.
  • Mutation: is the only method that changes the state in the store, and must be a synchronization function.
  • Action: Used to commit mutation rather than directly change the state, and can include any asynchronous operation.
  • Module: Allows you to split a single Store into multiple stores and Store them simultaneously in a single state tree.

The ultimate star yao

18. What should be done with data that does not require responsiveness?

In our Vue development, there will be some data, from beginning to end all have not changed, the death data, now that don’t change, that also don’t need to be responsive to him processing, otherwise will only do some useless consumption performance, such as some writing death drop-down box, die form data, the data of death data, if all responsive processing, That will consume a lot of performance.

// Method 1: Defines the data in the data outside the data () {enclosing list1 = {XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX} this. List2 = {XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}  this.list3 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } this.list4 = { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } this.list5 = { Return XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX} {}} / / method 2: Object. Freeze () the data () {return {list1: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list2: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list3: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list4: Object.freeze({xxxxxxxxxxxxxxxxxxxxxxxx}), list5: Object.freeze({XXXXXXXXXXXXXXXXXXXXXXXX}),}} Copy the codeCopy the code

19. What are the attributes of watch and what are their uses?

When we listen for a basic data type:

Watch: {value () {// do something}} copy the codeCopy the code

When we listen on a reference data type:

Watch: {obj: {handler () {// execute the callback // do something}, deep: true, // Whether to listen deeply on the immediate: True // Whether the handler function}} is initially executed to copy the codeCopy the code

20. Parent-child component lifecycle order

Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted

21. New properties of objects cannot update views. Deleting properties cannot update views. How to do?

  • The reason:Object.definePropertyThere is no property hijacking of the new property of the object
  • Object new property cannot update view: useVue.$set(obj, key, value), a component ofthis.$set(obj, key, value)
  • Delete property cannot update view: useVue.$delete(obj, key), a component ofthis.$delete(obj, key)

Arr [index] = XXX Why is that? How to do?

  • Cause: Vue does not perform on arraysObject.definePropertyArr [index] = XXX does not update the view
  • Using the array splice method,arr.splice(index, 1, item)
  • useVue.$set(arr, index, value)

23. Custom instructions

See this article for 8 very useful Vue custom directives

24. How does the slot work?

Do you really know how to “insert” a Slot

25. Why not use index as key and random number as key?

Here’s an example:

< div v - for = "(item, index) in the list" : the key = "index" > {{item. The name}} < / div > list: [{name: "xiao Ming, id: '123'}, {name: }, {name: 'xiaohong ', id: '124'} Played out in the '125'}] xiaoming < div key = "0" > < / div > < div key = "1" > red < / div > < div key = "2" > florets < / div > now I perform a list. The unshift ({name: 'xiao Lin, id: '122'}) rendering for < div key = "0" > kobayashi < / div > < div key = "1" > xiaoming < / div > < div key = "2" > red < / div > < div key = "3" > floret < / div > contrast between the old and the new < div Xiao Ming key = "0" > < / div > < div key = "0" > kobayashi < / div > < div key = "1" > red < / div > < div key = "1" > xiaoming < / div > < div key = "2" > florets < / div > < div Key ="2"> red </div> <div key="3"> floret </div> Render as <div key="123"> Xiaoming </div> <div key="124"> Xiaoming </div> <div key="125"> Floret </div> Now I execute list.unshift({name: 'Xiaolin ', id: '122'}), Rendering for < div key = "122" > kobayashi < / div > < div key = "123" > xiaoming < / div > < div key = "124" > red < / div > < div key = "125" > floret < / div > contrast between the old and the new < div Key = "122" > kobayashi < / div > < div key = "123" > xiaoming < / div > < div key = "123" > xiaoming < / div > < div key = "124" > red < / div > < div key = "124" > red < / div > < div <div key="125"> <div key="125"> <div key="125"> <div </divCopy the code

It is the same with index and random number. Random number changes every time, so it can not be specific. It is very deceitful to men who play with women’s feelings, and it also consumes performance

26. Tell me about nextTick?

Let me give you an example, in VUE:

This. name = 'Lin Sanxin' this.age = 18 this.gender = 'male' copy codeCopy the code

We changed three variables, so the question is, is the DOM updated every time we change it? No, Vue uses an asynchronous update strategy. Generally speaking, a view will be updated at the same time for multiple changes in the same event loop, so as to save performance

If you understand the above, you should also understand the following example:

<div ref="testDiv">{{name}}</div> name: 'Lin' this.name = 'Lin three heart' console.log(this.$refs.testdiv.innerhtmlCopy the code

The answer is “Kobayashi”, as mentioned above, Vue is an asynchronous update, so the data is updated, but the view is not updated, so the data is still the old view data, so how to get the latest view data?

This. Name = 'refs.testdiv.innerhtml' this.$nextTick(() => {console.log(this.$refs.testdiv.innerhtml) // lintr.innerhtml)Copy the code

27. What is SSR of Vue? What are the benefits?

  • SSRIt’s server side rendering
  • Based on thenodejs serveService environment development, allhtmlThe code is rendered on the server side
  • The data is returned to the front end, which then “activates” it and becomes HTML code that the browser recognizes
  • SSRThe crawler can see the content of the whole page. If it is a Vue project, the data has to be analyzed, so the crawler will not wait for the completion of your data loading. Therefore, the SEO experience of a Vue project is not very good

Most of the king

28. How is the Vue response realized?

The whole idea is data hijacking + observer mode

Attributes are internally hijacked using object.defineProperty (only existing attributes are hijacked) via the defineReactive method, while arrays are done by overriding array methods. When a page uses a corresponding attribute, each attribute has its own DEP attribute, which stores the watcher it depends on (dependent collection). When the attribute changes, the corresponding Watcher will be notified to update (distributed update).

To learn more about the process, I recommend reading my Vue source code parsing 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}}) Copies the codeCopy the code

29. Why only object hijacking, but array method rewriting?

Because the object only has dozens of attributes at most, the number of interception is not large, but the array may have hundreds of thousands of items, interception is very performance consuming, so directly rewriting the method on the array prototype is relatively cost-effective

30. How does Vue template compilation work?

Because this is a long question, so:

I suggest reading this “Vue source learning (2)” you do not know – template compilation principle

31. How does Vue compute and watch work?

Because this is a long question, so:

I suggest you read my article “Learning Vue source code (4)” and aim to write about the principle of computed and watch that everyone can understand

32. How does vue.set work?

function set(target, key, If (array.isarray (target)) {target. Length = math.max (target. Splice target.splice(key, 1, val) return val} const ob = target.__ob__ // If this object is not a responsive object, Set and return if (key in target &&! (key in target.prototype) || ! Ob) {target[key] = val return val} // otherwise, add attributes and respond to defineReactive(target, key, val) return val} copy codeCopy the code

33. How does vue. delete work?

Function del (target, key) {if (array.isarray (target)) { 1) return} const ob = target.__ob__ // If (! (key in target)) return // Delete target[key] // If (! Ob) return // If yes, notify the view to update the ob.dep.notify()} copy code after deletionCopy the code

34. How does nextTick work?

let callbacks = []; // Let pending = false; function flushCallbacks() { pending = false; For (let I = 0; i < callbacks.length; i++) { callbacks[i](); } } let timerFunc; If (Typeof Promise! Const p = promise.resolve (); timerFunc = () => { p.then(flushCallbacks); }; } else if (typeof MutationObserver ! == "undefined") {// 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 ! Setimerfunc = () => {setImmediate(flushCallbacks); }; } else {setTimeout timerFunc = () => {setTimeout(flushCallbacks, 0); }; } export function nextTick(cb) { callbacks.push(cb); if (! pending) { pending = true; timerFunc(); }} Copy the codeCopy the code

35. What’s the use of key? What about diff?

Why not use index as key in Vue? (Diff algorithm details)

I don’t speak it so well as he does

Knowledge points that are not popular

36. What happens if a child component changes the data in props

  • The changed props data is of the basic type

If you modify a base type, an error is reported

Props: {num: Number,} created() {this.num = 999Copy the code

  • The changed props data is a reference type
Function: {item: {default: () => ({}),}} created() {// This.item.name = 'sanxin'; This. item = 'SSS'}, copy codeCopy the code

37. How to customize props

props: { num: { default: 1, validator: Function (value) {return [1, 2, 3, 4, 5].indexof (value)! == -1}}} copy the codeCopy the code

38. What is the use of the immediate attribute of watch?

For example, when created requests data once and when the search value changes, we would write:

Created (){this.getList()}, watch: {searchInputValue(){this.getList()}} Copy codeCopy the code

You can write this with immediate, which is executed initially when true

Watch :{searchInputValue:{handler: 'getList', immediate: true}} Copies the codeCopy the code

39. When watch is listening to an object, how to exclude certain attributes from listening

If params changes, request data again, whether a, B, C, d attribute changes

data() { return { params: { a: 1, b: 2, c: 3, d: 4 }, }; }, watch: { params: { deep: true, handler() { this.getList; },},} copy the codeCopy the code

But what if I just want to ask again when A, B changes, and not ask again when C, D changes?

mounted() { Object.keys(this.params) .filter((_) => ! [r]. "c", "d" includes (_)) / / out of c, d attribute listening. ForEach ((_) = > {enclosing $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 the codeCopy the code

40. What is data-V-xxxxx found when reviewing elements?

This is the result of using the scoped tag when marking CSS in vue files. To ensure that CSS in files do not interfere with each other, each component is uniquely marked, so a new ‘data-v-xxx’ tag appears every time a Component is introduced

41. How does computed parameter transfer work?

// HTML <div>{{total(3)}} // js computed: {total() {return function(n) {return n * this.num}},} Copies codeCopy the code

42. Use of hook of Vue

  • Used in the same component

This is the way we usually use timers

Export default{data(){timer:null}, mounted(){this.timer = setInterval(()=>{console.log('1'); }, 1000); } beforeDestory(){ clearInterval(this.timer); this.timer = null; }} Copy the codeCopy the code

The problem is that you need to define a timer variable globally. You can use hook to do this:

Export default{methods:{fn(){let timer = setInterval(()=>{console.log('1'); }, 1000); this.$once('hook:beforeDestroy',()=>{ clearInterval(timer); timer = null; })}}} copy the codeCopy the code
  • 7.2 Using Parent and Child Components

/ / if a child component needs to trigger a function of its parent when mounted,

< rl-child-@childMounted ="childMountedHandle" /> method () {childMountedHandle() {do something... $emit() {this.$emit('childMounted')Copy the code

Hook can be more convenient:

<rl-child @hook:mounted="childMountedHandle" /> method () {childMountedHandle() {// do something... }}, copy the codeCopy the code

43. Are provide and Inject responsive?

// Provide (){return {// keyName: {name: this.name}, // provide(){return {// keyName: {name: this.name}, // This.changevalue () = this.changevalue () = this.changevalue () Data (){return {name:' name '}}, methods: {changeValue(){this.name = 'Changed name - Li 4'}} // Descendant component inject:['keyName'] create(){console.log(this.keyname) // Changed name - Li 4 } Duplicate codeCopy the code

44.Vue’s EL attribute and $mount priority?

For example, in the following case, which node Vue will render to

New Vue({router, store, el: '#app', render: h => h(app)}).$mount('# GGG 'Copy the code

If el and $mount exist together, 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 codeCopy the code

46. How are the same routing components re-rendered?

Developers often encounter situations where multiple routes resolve to the same Vue component. The problem is that Vue will not re-render shared components by default for performance reasons, and nothing will change if you try to switch between routes that use the same component.

const routes = [ { path: "/a", component: MyComponent }, { path: "/b", component: MyComponent }, ]; Copy the codeCopy the code

What if I still want to re-render? You can use keys

<template> <router-view :key="$route.path"></router-view> </template> copy the codeCopy the code

47. Custom V-Model

By default, v-model is the syntax sugar on the @Input event listener and the :value property. However, you can specify a model property in your Vue component that defines what event and value properties to use — great!

Export default: {model: {event: 'change', prop: 'checked'}} Copy the codeCopy the code

48. How to obtain the initial state of a data in data?

In development, sometimes you need to calculate the initial state. For example,

data() { return { num: 10 }, mounted() { this.num = 1000 }, methods: {howMuch() {// calculate howMuch num increases, $options.data().xxx console.log(1000 - this.$options.data().num)}} copy codeCopy the code

49. Why not suggest that v-for and V-IF coexist

<div v-for="item in [1, 2, 3, 4, 5, 6, 7]" v-if="item ! {{item}} </div> Copy codeCopy the code

If v-for and V-if exist at the same time, it traverses all 7 elements first, then determines whether they are 3 one by one and hides the 3. The disadvantage of this is that it renders useless 3 nodes and increases useless DOM operations. It is recommended to solve this problem using computed data:

<div v-for="item in list"> {{item}} </div> computed() { list() { return [1, 2, 3, 4, 5, 6, 7].filter(item => item ! == 3)}} Copy the codeCopy the code

50. Which is better, methods or computed, in calculating variables?

<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 the codeCopy the code

Computed is better, because computed has a cache. For example, if index changes from 0 to 1, it triggers a view update, and methods executes again, but computed does not, because num and price remain the same as the two variables computed depends on.

From the original link @sunshine_lin:Juejin. Cn/post / 698421…

\