Today, I would like to share with you the knowledge of the test questions that Vue often meets

1. What is the vUE lifecycle?

The lifecycle of a Vue instance is the process from creation to destruction. The process of creating, initializing data, compiling templates, mounting DOM-> rendering, updating -> rendering, unmounting, etc., is called the Vue life cycle.

2. What is the role of the VUE lifecycle?

It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of an entire VUE instance.

3. How many phases are there in the Vue life cycle?

It can be divided into 8 stages altogether: before/after creation, before/after load, before/after update, and before/after destruction

4. Which hooks will be triggered the first time the page loads?

The first page load triggered when beforeCreate, created, beforeMount, mounted

5. In which cycle is DOM rendering completed?

DOM rendering is done in Mounted

6. Some ways to use lifecycle hooks:

Mounted displays the loading event for both applications and for both applications. Mounted displays the loading event for both applications and for both applications. Mounted displays the loading event for both applications. Get the DOM node 4. Updated: Corresponding function if data is handled uniformly 5. BeforeDestroy: an acknowledgement box that acknowledges stop events 6Copy the code

7. Difference between V-show and V-IF

V-show is CSS toggles, v-if is complete destruction and re-creation using V-show for frequent toggles, v-if for less changes at runtime v-if = ‘false’ V-if is conditional rendering, it won’t render when false if v-if is true, if it is false, So the page will not have this HTML tag and it will generate a V-show and the HTML element will exist regardless of whether the value is true or false, but display or hide the V-show in the CSS just controls how the element is displayed, Toggle the display property back and forth between block and None; V-if controls the presence or absence of the DOM node. When we need to switch the show/hide of an element frequently, using V-show is more cost-effective in terms of performance; Using V-if makes more sense when you only need to show or hide once.

8. What are the common instructions used in development?

V-model is used to express input, making it easy to bind form controls and data in both ways. V-html is used to update the innerHTML of an element, v-show is used to conditionally render an element, v-on:click is used to bind an event. If the event is triggered, you can specify the event handler v-for: to render the element or template multiple times based on the source data V-bind: to apply the DOM syntax in response to changes in the value of the expression v-bind:title= “MSG” short :title= “MSG”

9. Bind array usage of class

V-bind :class="{'orange':isRipe, 'green':isNotRipe} "2. Array method V-bind :class="[class1,class2]" 3 Inline v - bind: style = "{color: color, fontSize: fontSize + 'px'}"Copy the code

10. Route forward mode

1. Router-link tags are rendered as tags. Router.push (‘/home’)

11.MVVM

M-model, where model stands for data model, can also define the business logic for data modification and manipulation

V-view, which stands for UI component, is responsible for converting the data model into A UI presentation

Vm-viewmodel, a viewModel listens to changes in model data, controls view behavior, and handles user interactions. Simply understood, it is an object that synchronizes view and Model, and connects model and View

What’s the difference between Puted and Watch

computed

Computed is a computed property, computed value, and it’s used more in scenarios where values are computed computed is cacheable, computed values are cached after the getter is executed, and only after the value of the property that it depends on changes, The next time the value of computed is obtained, the corresponding getter is invoked to compute computed

watch

Watch is more of a [watch] function, similar to a listening callback for some data, which is used to observe the props $emit or the value of this component. When the data changes, the callback is executed for subsequent operations without caching, and the page is re-rendered without changing the value

summary

When we’re doing numerical calculations, and we’re relying on other data, let’s design this for computed and if you need to do something when the data changes, use watch to see what the data changes.

13. The role of the vue component’s Scoped property

Add the scoped attribute to the style tag to indicate that the style applies to the current module, which is a good way to privatize the style. But be careful: styles are not easy to change, and many times you need to tweak the styles of common components;

Solutions:

If you want one of the selectors in scoped to be “deeper”, such as affecting sub-components, you can use the >>> operator: .a >>> .b { /* … * /}

14. Understanding that vue is an incremental framework :(claim the least, do not go beyond the call of duty)

Vue’s core function is a view template engine, but that doesn’t mean Vue can’t be a framework. As you can see below, this includes all the parts of Vue. Based on declarative rendering (view template engine), we can build a complete framework by adding component systems, client routing, and large-scale state management. What’s more, these functions are independent of each other, and you can build on top of the core function with whatever parts you want, not all of them. It can be seen that the “progressive” is actually the way Vue is used, and also reflects the design concept of Vue. In my opinion, the progressive means: the least proposition. Each view template engine framework will inevitably have its own characteristics, which will have certain requirements on users. These requirements are propositions, strong or weak, which will affect how they are used in business development. Angular, for example, is strongly enforced in both versions, and if you use it, you must accept the following: You have to use its module mechanism – you have to use its dependency injection – you have to use its special form to define components (which every view framework has, and it’s hard to avoid). So Angular is highly exclusive. If your application is not starting from scratch, but is constantly considering whether to integrate with something else, Such claims cause some confusion. Vue may be worse than React or Angular in some ways, but it’s evolutionary and not compelling. You can implement a component or two on top of a larger system like jQuery. You can also use it for whole family development, when Angular uses it; You can also use its view with an entire lower layer of your own design. It could be functional, it could be anything, it’s just a lightweight view, it’s just doing what it should be doing, it’s not doing what it shouldn’t be doing, that’s all. Incremental means, as I understand it, not doing more than you’re supposed to.

15. What are the two cores of vue.js (data-driven, component system)?

Data driven :Object.defineProperty and storage properties: getter and setter (so only compatible with IE9 and above), can be called the observation mechanism based on dependency collection, the core is VM, namely ViewModel, to ensure the consistency of data and view. Component systems: Click here to view

16. Vue common modifier

Lazy: The V-model synchronizes the value of the input box with the data after each input event is triggered. You can change to synchronization using the change event by adding the lazy modifier

<input v-model.lazy="msg" >  
Copy the code

.number

<input v-model.number="age" type="number">
Copy the code

.trim

<input V-model. trim='trim'>Copy the code

② Event modifier

<a v-on:click.stop="doThis"></a><! <form V-on :submit. Prevent ="onSubmit"></form> <! - submit event no longer reloading the page - > < v - on a: click. Stop. Prevent = "doThat" > < / a > <! <form V-on :submit. Prevent ></form> <! <div V-on :click.capture="doThis"> <div V-on :click.capture="doThis">... </div> <! -- Use event capture mode when adding event listeners --> <! <div v-on:click.self="doThat"> <div v-on:click.self="doThat"> </div> <! Trigger handler only if event.target is the current element itself --> <! That event is not triggered from internal elements - > < v - on a: click once = "doThis" > < / a > <! Click event will only trigger once -->Copy the code

Key modifiers all key aliases:

.enter.tab.delete (capture "delete" and "backspace" keys).ESC.space.up.down.left.right. Ctrl.alt.shift. meta <input V-on :keyup. Enter ="submit"> or < input.keyup. Enter ="submit">Copy the code

(4) System modifier (the following modifier can be used to implement the listener that only triggers the mouse or keyboard event when the corresponding key is pressed.)

.ctrl.alt.shift. meta <input @keyup.alt.67="clear"> or <div @click. CTRL ="doSomething">Do something</div><! -- Ctrl + Click -->Copy the code

17. Can V-ON listen for multiple methods? (Yes)

Two ways to bind events to an element, two ways to bind functions to an event, use of modifiers.

<a style="cursor:default" v-on='{click:DoSomething,mouseleave:MouseLeave}'>doSomething</a>
Copy the code

Write two time events inside the method.

<button @click="a(),b()">Copy the code

18. How are event objects used in VUE events

<button @click="Event($Event)">Copy the code

19. For example, if you want a DOM element to display, the next step is to get the element’s offsetWidth. You’ll get 0.

Because you change the data to show to true, the element is not immediately displayed and, of course, does not get the dynamic width. The correct way to do this is to show the element first and perform the width fetch operation in $nextTick.

OpenSubmenu () {this.show = true this.$nextTick() => let w = this. })}Copy the code

20. Why must data be a function in a Vue component

The value of data in a VUE component cannot be an object because objects are reference types and components may be referenced by multiple instances at the same time. If the value of data is an object, multiple instances will share the same object, and one component will change the value of the data attribute, affecting the other instances as well.

21. The vUE subcomponent calls the parent component’s method

The first method is to call the parent component’s methods directly in the child with this.parent. Event. The second method is to call the parent component’s methods in the child with parent-event The second method is to emit an event from the child component to the parent component, and the parent component listens for the event. The third method can implement the child to call the parent,

<template> <div> < button@click ="childMethod()"> click </button> </div> </template> <script> export default {props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { if (this.fatherMethod) { this.fatherMethod(); }}}}; </script>Copy the code

22. Function of keep-alive component in Vue

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.

<keep-alive> <component> <! This component will be cached! --> </component> </keep-alive> Export default [{path: '/', name: 'home', component: Home, meta: {keepAlive: true // Need to be cached}}, {path: '/:id', name: 'edit', Component: edit, meta: {keepAlive: }}] <keep-alive> <router-view v-if="$route.meta. KeepAlive "> <! -- Here are the view components that will be cached, such as Home! --> </router-view> </keep-alive> <router-view v-if="! $route.meta.keepAlive"> <! -- Here are view components that are not cached, such as Edit! --> </router-view>Copy the code

23. How to write reusable components in VUE?

Go here and have a look

blog.csdn.net

] (link.zhihu.com/?target=htt…).

① Create a component page eg toasts.vue; (2) Extend a component constructor with vue.extend () and create reusable components by instantiating the component constructor; (3) Mount the Toast component on the newly created div; Add the TOAST component DOM to the body; ⑤ Modify and optimize to achieve dynamic control page display text with display time;

import Vue from 'vue'; import Toast from '@/components/Toast'; ToastConstructor = Vue. Extend (Toast) // Return an "extended instance constructor" let myToast = (text,duration)=>{let toastDom = new ToastConstructor ({el: the document. The createElement method (' div ') / / will toast component mounted on the newly created div}) document. The body. The appendChild (toastDom. $el) Toastdom.text = text; toastDom.duration = duration; SetTimeout (()=>{toastdom.isshow = false; toastdom.isshow = false; }, toastDom.duration); } export default myToast;Copy the code

24. What are the VUE lifecycle and lifecycle hook functions?

Beforecreated: El and data are not initialized after the instance is initialized. Created: data is initialized, el is not (at this point, data and methods in the vue instance can be manipulated, but “dom” nodes cannot be manipulated;) BeforeMount: Completes initialization of EL and data // where EL is a virtual DOM; Mounted: Initiates a back-end request to retrieve data and performs routing tasks with the hook. BeforeUpdate: Refers to the view layer data change before, not data in the data change before trigger; Update: refers to view layer after data changes, beforeDestory: are you sure to delete XX? Destoryed: The current component has been deleted, clear the related content a. What is the VUE lifecycle? The lifecycle of a Vue instance is the process from creation to destruction. We call this the life cycle of a Vue, which starts with creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and unmounting. B. What is the role of the VUE life cycle? Its lifecycle has multiple event hooks, making it easier to form good logic when controlling the entire Vue instance. C. How many stages are there in the VUE life cycle? It can be divided into 8 stages: create before/after, load before/after, update before/after, destroy before/destroy d. Which hooks will be triggered the first time the page loads? BeforeCreate, Created, beforeMount, and Mounted are triggered the first time the page is loaded. In which cycle is DOM rendering completed? DOM rendering is done in Mounted. F. Simply describe which scenarios are suitable for each cycle? Mounted can be used for either of the loading events or for both of the loading events. Mounted can be used for either of the loading events or for both of the loading events. BeforeDestroy: Can make an acknowledgement stop event with an acknowledgement box nextTick: Update data immediately after operation DOM;

25. Vue’s method for triggering view updates when updating an array

Vue. Set ==========Vue. Set (target,key,value) $set(indexOfItem, newValue) vue. set(obj, keyOfItem, $set(keyOfItem, newValue) vue. delete This.obj.$set(keyOfItem, newValue) vue. delete Vue.delete(array, indexOfItem) this.array.$delete(indexOfItem) Vue.delete(obj, keyOfItem) this.obj.$delete(keyOfItem)Copy the code

26. Compilation principle of Webpack

Webpack interview questions summary

www.jianshu.com! [] icon (https://p3-juejin….

The role of webpack

(1) Dependency management: it is convenient to reference third-party modules, make modules easier to reuse, avoid conflicts caused by global injection, avoid repeated loading or loading unnecessary modules. Read dependent modules layer by layer, adding different entries; At the same time, dependent modules are not repackaged. (2) Merge code: pack the scattered modules into a large file, reduce the number of HTTP request links, with UglifyJS (compression code) can reduce, optimize the volume of the code. 3, various plugins: unified processing of imported plugins, Babel compile ES6 files, TypeScript, ESLint can check compile-time errors. In summary: ** WebPack is used to handle dependencies, modularize, package compressed files, and manage plug-ins. Everything is a module, since Webpack only supports JS files, so need to use loader to convert to webPack-supported modules, where plugin is used to expand the functionality of Webpack, in the process of WebPack build life cycle, do the right thing at the right time.

How does Webpack work

(1) Parse the configuration parameters, merge the configuration information from shell(NPM install similar command) and webpack.config.js file, output the final configuration information; (2) Register the plug-in in the configuration, let the plug-in listen to the event node in the WebPack construction life cycle, and make the corresponding response; (3) Parse the entry file in the configuration file, and find the file that each file depends on, recursively; (4) In the recursive process of each file, find out the corresponding Loader according to the file type and loader in the configuration file and convert the file; ⑤ Get the final result of each file after the recursion, and generate code chunk(the name after packaging) according to entry configuration; ⑥ Output all chunks to the file system.

27. Single-page applications such as Vue and their advantages and disadvantages

Disadvantages:

Browsers of earlier versions are not supported. Internet Explorer 9 at least is supported. Not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); The first time to load the home page is relatively long; You can’t use the browser’s navigation buttons. You need to move forward and backward.

Advantages:

No refresh experience, improve user experience; Front-end development is no longer based on the page as a unit, more componentized thought, code structure and organization more standardized, easy to modify and adjust; API sharing, the same back-end program code can be used for Web interface, mobile phone, tablet and other clients without modification good user experience, fast, content changes do not need to reload the whole page.

28. What is vUE’s computed attribute computed

Calculating attributes requires complex logic and can be replaced by methods

computed:{ totalPrice(){ return (this.good.price*this.good.count)*this.discount+this.deliver; }}Copy the code

29. Vue-cli provides several scaffold templates

Vue-cli scaffolding project templates are Browserify and Webpack;

30. Pass data in components?

Props: export default {props: {message: String}, // or props:["message"] data: {} the parent component calls the method of child components: the parent component enclosing $refs. Yeluosen. ChildMethod () child components to the parent component values and call the method transfer $emit between components: bus = = $emit + $onCopy the code

31. Vue-router implements lazy route loading (dynamic route loading)

32. Vue-router navigation hook, mainly used to intercept navigation, let it complete the jump or cancel.

** Global :** Front-guard, post-hook (beforeEach, afterEach) beforeResolve ** Single route exclusive :**beforeEnter component-level: BeforeRouteEnter (cannot get component instances this), beforeRouteUpdate, beforeRouteLeave This is because the component has not yet been created when the routing hook function beforRouteEnter is executed. For example, next((VM)=>{}). The parameter VM is the instantiation object of the component.

33. Complete vue-Router navigation parsing process

1. Navigation is triggered. 2. Call the beforeRouteLeave guard in the deactivated component; 3. Call the global beforeEach guard; 4. Call the beforeRouteUpdate guard in the reuse component; 5. Invoke the beforeEnter guard in the routing configuration. 6. Parse asynchronous routing components. 7. Call the beforeRouteEnter guard in the activated component; 8. Call the global beforeResolve guard; 9. Navigation is confirmed; 10.. Call the global afterEach hook; 11. The DOM updates; 12. Call the callback passed to Next in the beforeRouteEnter guard with the created instance.

34. How does vue-Router respond to route parameter changes?

The original component instance is reused. This also means that the component’s lifecycle hooks are no longer called. You can simply watch the $route object:

const User = { template: '... ', watch: {$route '(to and from) {/ / right by changes to respond... } } } const User = { template: '... ', watch: {$route '(to and from) {/ / right by changes to respond... }}}Copy the code

35. Several examples of vue-router and parameter transfer

The name is passed to using the URL

36. Usage of IS (for dynamic components and works based on the limitations of templates in the DOM.)

Is is used to dynamically switch components and DOM template parsing

<table> <tr is="my-row"></tr> </table>
Copy the code

37. What is vuex? How to use it? Which functional scenarios use it?

State management in vUE framework: there are five types of State management, including State, Getter, Mutation, Action, Module. Use: Create a directory store, scenario: single page application, State between components. Music play, login status, add shopping cart

The State feature of VUex A, VUex is A warehouse with many objects in it. Where state is where data source is stored, corresponding to the general Vue object data B, the data stored in state is responsive, the Vue component reads data from store, if the data in store changes, Components that depend on this data are updated C, which maps global state and getters to vuex's getters feature in computed properties of the current component using mapState. A, getters can calculate state. C. If a state is only used within a component, The only way to change the state of a store without the Mutation feature of Getters Vuex is to submit Mutation, which is a similar event. Each mutation has a string event type and a callback function where we need to change the value of state. To execute this callback, we need to execute a corresponding calling method: store.mit. Actions are similar to mutation, except that they commit mutations instead of directly changing the state. The Action function accepts a context object with the same methods and properties as the store instance, so you can submit a mutation by calling context.mit. Or get state and getters via context.state and context.getters. Action is triggered by the store.dispatch method: eg. Store. dispatch('increment') Vuex's Module feature, Module, actually solves the problem that when state is very complex and bloated, module can split store into modules. Each module has its own state, mutation, action, and getterCopy the code