Home > Web Front-end > JS Tutorial > body text

Nine common vuejs interview questions, do you know them?

PHPz
Release: 2020-07-31 14:03:41
Original
8388 people have browsed it

11 common vuejs interview questions, do you know them? From vue interview questions column

1. Understanding MVVM?

MVVM is the abbreviation of Model-View-ViewModel
Model represents the data model, and business logic for data modification and operation can also be defined in the Model.
View represents the UI component, which is responsible for converting the data model into UI display.
ViewModel monitors changes in model data, controls view behavior, and handles user interaction. A simple understanding is an object that synchronizes View and Model and connects Model and View.
Under the MVVM architecture, there is no direct connection between View and Model. Instead, they interact through ViewModel. The interaction between Model and ViewModel is two-way, so changes in View data will be synchronized to the Model, and the Model Changes in data will also be immediately reflected on the View.
ViewModel connects the View layer and the Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention, so developers only need to focus on business logic and do not need manual operations. DOM does not need to pay attention to the synchronization of data status. Complex data status maintenance is completely managed by MVVM.

2. The life cycle of Vue

beforeCreate(before creation)

Before the data observation and initialization events have started

created(after creation)

Complete data observation, operation of properties and methods, initialization events, el attribute has not yet been displayed

beforeMount (before loading)

is called before the mounting starts, The relevant render function is called for the first time. The instance has completed the following configuration: compile the template, and generate html from the data in the data and the template. Note that the html has not been mounted on the page at this time.

mounted (after loading)

Called after el is replaced by the newly created vm.$el and mounted to the instance. The instance has completed the following configuration: replace the DOM object pointed to by the el attribute with the compiled html content above. Complete the rendering of the html in the template into the html page. Ajax interaction is performed during this process.

beforeUpdate (before update)

Called before the data is updated, which occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering an additional re-rendering process.

updated

Called after virtual DOM re-rendering and patching due to data changes. When called, the component DOM has been updated, so DOM-dependent operations can be performed. In most cases, however, changing state during this period should be avoided, as this may cause an infinite loop of updates. This hook is not called during server-side rendering.

beforeDestroy (before destruction)

Called before the instance is destroyed. The instance is still fully available.

destroyed (after destruction)

Called after the instance is destroyed. After calling, all event listeners will be removed and all child instances will be destroyed. This hook is not called during server-side rendering.

1. What is the vue life cycle?

Answer: The process from creation to destruction of a Vue instance is the life cycle. A series of processes from starting to create, initializing data, compiling templates, mounting Dom→rendering, updating→rendering, and destruction are called the life cycle of Vue.

2.What is the role of vue life cycle?

Answer: There are multiple event hooks in its life cycle, making it easier for us to form good logic when controlling the process of the entire Vue instance.

3. How many stages are there in the vue life cycle?

Answer: It can be divided into 8 stages in total: before/after creation, before/after loading, before/after update, before/after destruction.

4. Which hooks will be triggered when the page is loaded for the first time?

Answer: The following beforeCreate, created, beforeMount, mounted will be triggered.

5. In which cycle is DOM rendering completed?

Answer: DOM rendering is completed in mounted.

3. The principle of Vue to implement two-way data binding: Object.defineProperty()

Vue implements two-way data binding mainly by using data hijacking combined with the publisher-subscriber model. Use Object.defineProperty() to hijack the setters and getters of each property, publish messages to subscribers when the data changes, and trigger corresponding listening callbacks. When you pass a plain Javascript object to a Vue instance as its data option, Vue will iterate through its properties and convert them into getters/setters using Object.defineProperty. The getters/setters are not visible to the user, but internally they allow Vue to track dependencies and notify changes when properties are accessed and modified.

Vue's two-way data binding uses MVVM as the entrance to data binding, integrating Observer, Compile and Watcher. It uses Observer to monitor the data changes of its own model, and uses Compile to parse and compile template instructions (vue is used to parse {{}}), and finally uses watcher to build a communication bridge between observer and Compile to achieve data change -> view update; view interactive change (input) -> data model change two-way binding effect .



    <p>
        <input>
        </p><p></p>
    

<script>
    var obj = {}
    Object.defineProperty(obj, &#39;txt&#39;, {
        get: function () {
            return obj
        },
        set: function (newValue) {
            document.getElementById(&#39;txt&#39;).value = newValue
            document.getElementById(&#39;show&#39;).innerHTML = newValue
        }
    })
    document.addEventListener(&#39;keyup&#39;, function (e) {
        obj.txt = e.target.value
    })
</script>
Copy after login

4. Parameter transfer between Vue components

1. Value transfer between parent component and sub-component
Parent component passes to sub-component: sub-component receives data through props method;
Sub-component Passed to the parent component: $emit method passes parameters
2. Data transfer between non-parent and child components, sibling components pass values
eventBus is to create an event center, equivalent to a transfer station, which can be used to transfer events and Receive events. If the project is relatively small, this is more appropriate. (Although many people recommend using VUEX directly, it depends on the needs. Technology is just a means, and achieving the goal is the king.)

5. Vue’s routing implementation: hash mode and history mode

hash mode:

In the browser, the symbol "#", # and the characters after # are called hash, and are read with window.location.hash;
Features: Although hash is in the URL , but not included in the HTTP request; used to guide browser actions, useless for server-side security, and the hash will not reload the page.
In hash mode, only the content before the hash symbol will be included in the request, such as http://www.xxx.com. Therefore, for the backend, even if full coverage of routing is not achieved, A 404 error will be returned.

history mode:

history adopts the new features of HTML5; and provides two new methods: pushState(), replaceState() to modify the browser history stack, and the popState event to monitor status changes.
In history mode, the URL of the front end must be consistent with the URL that actually initiates the request to the back end, such as http://www.xxx.com/items/id. If the backend lacks routing processing for /items/id, a 404 error will be returned. The Vue-Router official website describes this: "However, to play well in this mode, it also requires background configuration support... Therefore, you need to add a candidate resource on the server side that covers all situations: if the URL does not match any static resources, Then the same index.html page should be returned, which is the page your app depends on."

6. The hook function of vue routing

The status that is only used to read is concentrated in the store Medium; The way to change the state is to submit mutations, which is a synchronous thing; asynchronous logic should be encapsulated in actions.
Introduce store into main.js and inject it. A new directory store is created,...export.
Scenarios include: In a single-page application, the state between components, music playback, login status, and adding to the shopping cart

state

Vuex uses a single state tree, that is, each application will Contains only one store instance, but a single state tree does not conflict with modularity. The stored data status cannot be modified directly.

mutations

The methods defined by mutations dynamically modify the state or data in the Vuex store.

getters

Computed properties similar to vue are mainly used to filter some data.

action

actions can be understood as changing the method of processing data in mutations into a method that can process data asynchronously. Simply put, it is asynchronous operation of data. The view layer distributes actions through store.dispath.

modules

When the project is particularly complex, each module can have its own state, mutation, action, and getters, making the structure very clear and easy to manage.

//store实例
const store = new Vuex.Store({ 
    state: {
        count: 0
    },
    mutations: {                
        increment (state) {
            state.count++
        }
    },
    actions: { 
        increment (context) {
            context.commit('increment')
        }
    }
})
Copy after login

7. How to add custom instructions to vue-cli?

1. Create local instructions
var app = new Vue({
    el: '#app',
    data: {    
    },
    // 创建指令(可以多个)
    directives: {
        // 指令名称
        dir1: {
            inserted(el) {
                // 指令中第一个参数是当前使用指令的DOM
                console.log(el);
                // 对DOM进行操作
                el.style.width = '200px';
                el.style.height = '200px';
                el.style.background = '#000';
            }
        }
    }
})
Copy after login
2. Global instructions
Vue.directive('dir2', {
    inserted(el) {
        console.log(el);
    }
})
Copy after login
3. Use of instructions
<p>
    </p><p></p>
    <p></p>
Copy after login

8. How to customize a filter in Vue ?

html code:
<p>
     <input>
     {{msg| capitalize }}
</p>
Copy after login
JS code:
var vm=new Vue({
    el:"#app",
    data:{
        msg:''
    },
    filters: {
      capitalize: function (value) {
        if (!value) return ''
        value = value.toString()
        return value.charAt(0).toUpperCase() + value.slice(1)
      }
    }
})
Copy after login
Global definition filter
Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})
Copy after login

9. Interview questions that can be answered in one sentence

1.css only works in the current component

Answer: Just write scoped in the style tag. For example:

2.v The difference between -if and v-show

Answer: v-if renders according to conditions, v-show is display block or none;

3.The difference between route and router

Answer: Nine common vuejs interview questions, do you know them?Router is a "routing instance" object that includes routing jump methods, hook functions, etc.

4.What are the two cores of vue.js?

Answer: Data-driven, component system

5. Several commonly used instructions in vue

Answer: v-for, v-if, v-bind, v-on , v-show, v-else

6. What are the commonly used modifiers in vue?

Answer: .prevent: The submit event will no longer reload the page; .stop: Prevent the click event from bubbling; .self: It will be triggered when the event occurs in the element itself rather than in the sub-element; .capture : Event listening,

7.v-on will be called when an event occurs. Can multiple methods be bound to v-on?

Answer: Yes

8. What is the role of key value in vue?

Answer: When Vue.js uses v-for to update the rendered element list, it defaults to the "in-place reuse" strategy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element there and make sure it displays each element that has been rendered at a specific index. The main role of key is to efficiently update the virtual DOM.

9.What are vue’s computed properties?

Answer: Putting too much logic in the template will make the template overweight and difficult to maintain. When complex processing of data is required and may be used multiple times, try to use calculated attributes. Benefits: ① Makes the data processing structure clear; ② Depends on the data, the data is updated, and the processing results are automatically updated; ③ This inside the calculated attribute points to the vm instance; ④ When the template is called, just write the calculated attribute name directly; ⑤ The commonly used getter method, to obtain data, you can also use the set method to change the data; ⑥ Compared with methods, methods will be recalculated regardless of the dependent data changing, but when the dependent data remains unchanged, computed will be obtained from the cache and will not be recalculated.

10.Single-page applications such as vue and their advantages and disadvantages

Answer: Advantages: The goal of Vue is to achieve responsive data binding and combined view components through the simplest possible API. The core is a reactive data binding system. MVVM, data-driven, componentized, lightweight, concise, efficient, fast, and module-friendly.
Disadvantages: Does not support lower version browsers, only supports IE9 at least; not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); it takes a relatively long time to load the homepage for the first time ;You cannot use the browser's navigation buttons and need to realize forward and backward by yourself.

11. How to define the dynamic routing of vue-router? How to get the passed value

Answer: In the index.js file in the router directory, add /:id to the path attribute , obtained using the params.id of the router object.

The above is the detailed content of Nine common vuejs interview questions, do you know them?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template