1. What are the advantages of the Vue framework?

(1) Lightweight framework: only focus on the view layer, only tens of Kb in size; (2) Simple and easy to learn: the document is smooth and clear with simple grammar; (3) Two-way data binding, data view structure separation, only need to operate the data to complete the corresponding page update; (4) Componentized development: clear engineering structure and convenient code maintenance; (5) Virtual DOM loading HTML nodes, high operation efficiency.

2. What is MVVM?

MVVM isModel-View-ModelViewIs an abbreviation of the MVC patternDesign patterns.

    Model represents the data layer, responsible for storing business-related data;

    View represents the View layer, responsible for displaying data on the page;

    ViewModel Yes, it synchronizes between the View and the ModelassociatedAnd the core of its synchronous association isDOM ListenersandData BindingsTwo tools.DOMListenersThe tool listens for DOM changes in the View and selectively passes them to the Model.Data BindingsThe tool listens for Model data changes and updates them to the View.



3. What are the methods of transferring values between components in Vue?

Parent component to child component:

(1) The parent component binds custom attributes in the child component tag; (2) The subcomponent receives via the props property.

/ / the parent component
export default { components:{ Child } }
<Child :name="123" />

/ / child component
export default { props: ["name"]// You can specify the data type}
Copy the code

Child component passes value to parent:

(1) Bind custom events in the parent component to the child component tag; (2) The child emits a custom event via the this.$emit() method, passing the value to the parent component.

/ / the parent component
export default { components:{ Child }, data: {name:"123" }, methods: {changeName(value){
this.name = value } } }
<Child @changeName="changeName" />

/ / child component
export default { methods: {changeParentName:(value) = >{ this.$emit("changeName"."456") } } }
<button @click="changeParentName"> change the name of the parent component </button>Copy the code

Passing values between sibling components:

(1) Common to the parent component, and then distributed by the parent component (state promotion); (2) Use Vuex; (3) Use bus event bus.

let bus = newMethods :{bus.$emit(' custom event name ', data)}/ / sendB component:created(){bus.$on(' A sends custom event name ', function)}// To receive data
Copy the code


4. What are the common lifecycle hook functions in Vue?

There are eight common lifecycle hook functions in Vue:

(1) Creation stage BeforeCreate: This function is called after Vue instance initialization, component creation, data Observer, and watch/ Event event configuration. At this time, data and REF cannot be accessed. Only life cycle functions and some default events exist on Vue instance objects. Created: This function is called after the Vue component is Created. At this point, the data monitoring and event configuration have been completed, the data object is accessible, but the component has not been rendered into an HTML template, ref is still undefined, and $el is not available.

To perform operations on the DOM in this phase, place the operations in vue.nexttick’s callback function. Because the DOM has not been rendered at this stage, DOM manipulation cannot be performed. Vue.nexttick executes a delayed callback after the next DOM update loop, and the updated DOM can be retrieved after the data is modified.

(2) Mount phase BeforeMount: This function is called before the component is mounted. At this point, the HTML template is compiled, the virtual DOM already exists, $EL is available, but ref is still unavailable.

The initial data acquisition is generally performed at this stage.

Mounted: This function is invoked after components are Mounted. The $el element has been replaced by vm.$el, and ref can operate on it.

Asynchronous requests are typically sent in this phase. Mounted does not ensure that all child components are mounted together. If you want to wait until the entire view is rendered, use vm.$nextTick inside Mounted.

(3) Update phase BeforeUpdate: This function is called before data update and virtual DOM patching.

This phase is suitable for accessing the existing DOM prior to updating, such as manually removing event listeners that have been added.

Updated: This function is invoked after data is Updated and the virtual DOM is patched.

(4) Uninstall phase BeforeDestory: This function is called before instance destruction, when the instance is fully available and ref still exists.

Performance optimization operations, such as clearing timers, are performed during this phase to prevent memory leaks.

Destroyed: Called after the instance is Destroyed. All instructions in the Vue are unbound, all event listeners are removed, and the ref state is undefined.

When a component is destroyed, the parent component is destroyed first and then the child component is destroyed.

There are two other hook functions for keep-alive components: activated: called when activated by a component cached by keep-alive. Deactivated: called when a component cached by keep-alive is disabled.

There is also an error-handling capture function:

        errorCaptured: called when an error is caught from a descendant component.

5. Why must data be a function in a Vue component?

If data is an object, when reusing components, because data points to the same reference type address, any changes to the data of one component will change the data of the other reused components as well. If data were a function that returns an object, this problem would not occur because each time a component is reused it returns a new object with a different reference address.

6. What is the difference between V-if and V-show in Vue?

When switching, v-if creates or destroys labels directly. Labels that are not displayed are not loaded into the DOM tree. When switching, v-show switches the display attribute of the label and hides the element by not displaying the display attribute. In general, v-if has a higher performance overhead than V-show, and v-show is more suitable for frequently switched labels.

7. What is the difference between computed and Watch in Vue?

Computed attributes (1) Supports caching, and only when the dependent data changes, the computed function is recalculated; (2) Asynchronous operation is not supported in computing attributes; (3) There is a get(default, get calculated property) and a set(manually add, set calculated property) method in the function to calculate the property; (4) The calculated attribute automatically listens to the change of the dependent value, so as to dynamically return the content.

Listen attribute watch: (1) Cache is not supported, as long as the data changes, the listener function will be executed; (2) Asynchronous operation is supported in the listening attribute; (3) The value of the listening attribute can be an object that receives handler callbacks, deep, and immediate. (3) Listening is a process that triggers a callback and does other things when the listening value changes.

watch: { 
	obj: { 
    	// Handler receives two arguments (newVal: new value, oldVal: old value)
    	handler: function(newVal, oldVal){ 
    		console.log(newVal); 
		}, 
	deep: true.// Set to true to listen for changes in the internal value of the object;
	immediate: true// Set to true immediately triggers a callback with the current value of the expression;}}Copy the code

Using immediate optimizes scenarios where components are created to retrieve the list data immediately, listen to the < INPUT /> box, and retrieve the filtered list every time it changes.

/ / before optimization
created(){ 
	this.fetchPostList() 
	}, 
watch: { 
	searchInputValue(){ this.fetchPostList() } 
	}
/ / after optimization
watch: { 
	searchInputValue: {handler: 'fetchPostList'.immediate: true}}Copy the code


8. What is $nextTick?

Instead of updating the DOM as soon as the data occurs, Vue implements responsiveness to perform deferred callbacks as soon as the next DOM update loop ends with vm.$nextTick. When used after the data has been modified, the updated DOM can be retrieved in the callback.

9. What is the function of key in V-for?

Key is the node identifier when Vue renders the list using V-for. After the key is used, when the list items change, Vue rearranges the element order based on the key change and removes the elements that do not exist in the key to improve operation efficiency.

10. What is the principle of two-way data binding for Vue?

Vue adopts the data hijacking + subscribe publishing model to achieve bidirectional binding. Add get and set methods to each attribute of data in the component via object.defineProperty (). When the data changes, the corresponding listener callback function in the set is triggered to publish the change information to the subscriber. The main steps are as follows: (1) component initialization: a. Create a DEP object as an observer (dependent on collection, subscription and publication carrier); B. Add getters and setters to attributes in data and subattributes of data via object.defineProperty (); When you call the getter, you register the function in the DEP. When the setter is called, the function you just registered is notified to execute. (2) When the component is mounted: A. compile parses the template instruction and replaces the variables in it with data. Then initialize render page view and update function and listen function on node binding corresponding to each instruction. The page is then updated whenever the data changes. Change information will be published when the page changes; B. The component also defines a Watcher class as a subscriber, and Watcher can serve as a bridge between the DEP and the component. When it is instantiated, it adds itself to the DEP. At the same time, it has an update method. When it receives notification of deP changes, it will call its update method and trigger the corresponding function in compile to complete the update.



11. How do I dynamically update the value of an object or array?

Because of object.defineProperty (), Vue cannot listen for changes in the value of a property inside an Object or array, so the page does not update in real time when the values of the above two types of data are set directly. $set = this.$set ();

//this.$set(array/object, position /key, value) this.$set(this.arr, 0, "OBKoro1");
$set(this.obj, "c", "OBKoro1"); $set(this.obj, "c", "OBKoro1"); // Change the object
Copy the code

Data updates caused by array native methods can be listened for by Vue. Such as the splice () push pop () (), etc.


12. What are common event modifiers?

. Stop: stop bubbling; Prevent: prevent default behavior; .self: Only the binding element itself can trigger; .once: triggers only once..

13. How does Vue get DOM elements?

First set the ref attribute for the tag element, then pass this.$refs. Property value acquisition.

<div ref="test"></div>

const dom = this.$refs.test
Copy the code


14. How does V-ON bind multiple events?

Multiple events can be bound by passing in a V-on object:

<! -- Single event binding -->
<input type="text" @click="onClick">
<! -- Multievent binding -->
<input type="text" v-on="{ input:onInput,focus:onFocus,blur:onBlur }">
Copy the code


15. How to solve the flash problem of Vue initialization page?

The problem is that before the Vue code is parsed, you have no control over how the DOM is displayed on the page, so you see code such as template strings. The solution is to add the V-cloak rule to the CSS code and add the V-cloak attribute to the tag to be compiled:

[v-cloak] { display: none; }

<div v-cloak>
  {{ message }}
</div>
Copy the code


16. How does Vue clear browser cache?

(1) When the project is packaged, add hash value to each packaged file, usually adding timestamp at the end of the file; (2) Add meta tags to HTML files and set content attribute to no-cache; (3) Disable cache Settings in the back-end server.

17. What are the modes of vue-router routing?

Generally, there are two modes: (1) Hash mode: When the hash value changes, the browser will not send a request to the server or refresh the hash value. The hashChange event will be triggered each time the hash value changes. (2) History mode: takes advantage of the new pushState() and replaceState() methods in HTML5. These two methods apply to the browser’s history stack and provide the ability to modify the history in addition to the existing back, Forward, and Go methods. It’s just that when they make changes that change the current URL, the browser doesn’t immediately send requests to the back end.

18. What is the general purpose of each folder and file in vue-CLI project?

(1) Bulid folder: store webpack-related configuration and script files, which are generally used to configure less, Babel and webpack.base.config.js files in actual development. (2) Config folder: The config.js (index.js) folder is used to configure the port number of the development environment, whether to enable hot loading or set the relative path of static resources in the production environment, whether to enable gzip compression, and the name and path of static resources generated by using the NPM run build command. (3) node_modules folder: stores dependencies of the development environment and production environment downloaded by NPM install. (4) SRC folder: store component source code, image style resources, entry files, routing configuration, etc.

19. What is the difference between assets and static folder in vue-CLI project?

Both are folders for the static resource files used in the project. The difference is that the files in ** assets are packaged when NPM Run build is run. In simple terms, the files are compressed, formatted and so on. It will also be put into static after packaging. Files in static are not packaged.

Unprocessed files such as pictures are placed in assets and packaged to reduce volume. Some imported resource files such as iconfont. CSS can be placed in static because they have already been processed.

20. What is Vuex? What are the properties?

Vuex is a state management tool designed for Vue and manages the state of all components in Vue with a centralized store.

(1) State attribute: basic data; (2) Getters property: data derived from state; (3) mutation attribute: ** the only way to update the data in the store, ** it receives a callback function with state as the first parameter;

const store = new Vuex.Store({
  state: {
    count: 1,},mutations: {
    increment(state) {
      // Change the statestate.count++; ,}}});Copy the code

(4) Action property: commit mutation to change state, which can include asynchronous operations;

const store = new Vuex.Store({
  state: {
    count: 0,},mutations: {
    increment(state){ state.count++; }},actions: {
    increment2(context) {
      context.commit('increment');
    },
    fun(context) {
      context.dispatch('increment2'); ,}}});Copy the code

(5) Module attribute: Used to divide store into different modules.

const moduleA = {
  state: () = >({... }),mutations: {... },actions: {... },getters: {... }}const moduleB = {
  state: () = >({... }),mutations: {... },actions: {... }}const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA status
store.state.b // -> moduleB status
Copy the code

Front End Interview Guide series portal:

Front-end interview Guide JS interview questions summary

Summary of HTML interview questions in the front-end Interview Guide

Front-end interview Guide CSS interview questions summary