Web front-end interview questions-vue aspect

Web front-end interview questions-vue aspect

1 What is mvvm?

MVVM is the abbreviation of Model-View-ViewModel. mvvm is a design idea. The Model layer represents the data model, and the business logic of data modification and operation can also be defined in the Model; View represents the UI component, which is responsible for transforming the data model into the UI for display, and the ViewModel is an object that synchronizes the View and the Model.

Under the MVVM architecture, there is no direct connection between the View and the Model, but the interaction through the ViewModel. The interaction between the Model and the ViewModel is two-way, so the changes in the View data will be synchronized to the Model, and the changes in the Model data It will also be reflected on the View immediately.

ViewModel connects the View layer and Model layer through two-way data binding, and the synchronization between View and Model is completely automatic without human intervention. Therefore, developers only need to focus on business logic and do not need to manually manipulate the DOM. Need to pay attention to the synchronization of data state, complex data state maintenance is completely managed by MVVM.

2 What is the difference between mvvm and mvc?

There is not much difference between mvc and mvvm. It is a design idea. Mainly, Controller in mvc evolved into viewModel in mvvm. mvvm mainly solves the problem that a large number of DOM operations in mvc reduce page rendering performance, slow down the loading speed, and affect user experience. And when the Model frequently changes, developers need to actively update the View.

3 What are the advantages of vue?

  • Low coupling. Views can be independent of model changes and modifications. A ViewModel can be bound to different "Views". When the View changes, the Model can remain unchanged, and when the Model changes, the View can also remain unchanged.
    Reusability. You can put some view logic in a ViewModel and let many views reuse this view logic.
  • Independent development. Developers can focus on business logic and data development (ViewModel), designers can focus on page design, and use Expression Blend to easily design interfaces and generate xml code.
  • Can be tested. Interfaces have always been difficult to test, but now tests can be written for ViewModel.

4 Please elaborate on your understanding of the vue life cycle?

Answer: There are 8 stages in total: before/after creation, before/after loading, before/after update, and before/after destruction.

  • Before/after creation: In the beforeCreate phase, the mount element el of the vue instance is not yet available.
  • Before/after loading: In the beforeMount phase, the $el and data of the vue instance are initialized, but they are still virtual dom nodes before mounting, and data.message has not been replaced. In the mounted phase, the vue instance is mounted and data.message is successfully rendered.
  • Before/after update: When the data changes, the beforeUpdate and updated methods are triggered.
    Before/after destruction: After the destroy method is executed, changes to the data will no longer trigger the periodic function, indicating that the vue instance has released the event monitoring and binding to the dom at this time, but the dom structure still exists

5 Passing values ​​between components?

Pass value between parent and child components

//父组件通过标签上面定义传值
<template>
    <Main :obj="data"></Main>
</template>
<script>
    //引入子组件
    import Main form "./main"

    exprot default{
        name:"parent",
        data(){
            return {
                data:"我要向子组件传递数据"
            }
        },
        //初始化组件
        components:{
            Main
        }
    }
</script>
//子组件通过props方法接受数据
<template>
    <div>{
   
   {data}}</div>
</template>
<script>
    exprot default{
        name:"son",
        //接受父组件传值
        props:["data"]
    }
</script>
子组件向父组件传递数据
//子组件通过$emit方法传递参数
<template>
   <div v-on:click="events"></div>
</template>
<script>
    //引入子组件
    import Main form "./main"

    exprot default{
        methods:{
            events:function(){

            }
        }
    }
</script>

//

<template>
    <div>{
   
   {data}}</div>
</template>
<script>
    exprot default{
        name:"son",
        //接受父组件传值
        props:["data"]
    }
</script>

6 Which component attribute is active-class?

The router-link component of the vue-router module.

7 How to define nested routing?

In actual projects, we will encounter multiple layers of nested components, but how do we implement nested routing? Therefore, we need to use children configuration in the parameters of VueRouter, so that routing nesting can be implemented well. index.html, only one route exit

<div id="app">
    <!-- router-view 路由出口, 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>
</div>
main.js,路由的重定向,就会在页面一加载的时候,就会将 home 组件显示出来,因为重定向指向了 home 组件,redirect 的指向与 path 的必须一致。children 里面是子路由,当然子路由里面还可以继续嵌套子路由。

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//引入两个组件

import home from "./home.vue"
import game from "./game.vue"
//定义路由
const routes = [
    { path: "/", redirect: "/home" },//重定向,指向了home组件
    {
        path: "/home", component: home,
        children: [
            { path: "/home/game", component: game }
        ]
    }
]
//创建路由实例
const router = new VueRouter({routes})

new Vue({
    el: '#app',
    data: {
    },
    methods: {
    },
    router
})
home.vue,点击显示就会将子路由显示在出来,子路由的出口必须在父路由里面,否则子路由无法显示。

8 Jump between routes?

  • Declarative (label jump)
  • Programmatic (js jump) router.push('index')

9 Lazy loading (load routing on demand) (often exam)

Webpack provides require.ensure() to implement on-demand loading. In the past, routes were imported through import, which was changed to const definition.


  • Import method without page loading on demand: import home from'…/…/common/home.vue'
  • The introduction method for page loading on demand:
    const home = r => require.ensure( [], () => r (require('…/…/common/home.vue')))

10 What is vuex? how to use? Which functional scenarios use it?

State management in the vue framework. Introduce store in main.js and inject. Create a new directory store,... export. The scenarios are: the state between components in a single-page application. Music playback, login status, add to shopping cart

// 新建 store.js
import vue from ‘vue’
import vuex form ‘vuex’
vue.use(vuex)
export default new vuex.store({
//…code
})

//main.js
import store from ‘./store’

11 What kind of navigation hooks does vue-router have?

Three kinds

  • 全局导航钩子
    router.beforeEach(to, from, next),
    router.beforeResolve(to, from, next),
    router.afterEach(to, from ,next)
  • 组件内钩子
    beforeRouteEnter,
    beforeRouteUpdate,
    beforeRouteLeave
  • Separate routing exclusive component
    beforeEnter

12 What are the methods for custom commands (v-check, v-focus)? What hook functions does it have? What other hook function parameters

  • Global definition directive: There are two parameters in the directive method of the vue object, one is the name of the directive, and the other is a function.
  • Define instructions in the component: directives
  • Hook function: bind (bound event start), inserted (triggered when the node is inserted), update (related update in the component)
  • Hook function parameters: el, binding

13 Name at least 4 commands in vue and their usage

v-if (judge whether to hide), v-for (traverse the data), v-bind (binding attributes), v-model (realizing two-way binding)

14 What is the principle of vue's two-way binding (frequently tested)

Vue.js uses data hijacking combined with the publisher-subscriber model to hijack the setter and getter of each property through Object.defineProperty(), publish messages to subscribers when the data changes, and trigger the corresponding listener callback.

Specific steps: Step 1: Recursive traversal of the data object that needs observe, including the properties of the sub-property object, plus setter and getter. In this case, assigning a value to this object will trigger the setter, and then you can monitor Data change

The second step: compile parses the template instructions, replaces the variables in the template with data, and then initializes the rendering page view, binds the update function to the node corresponding to each instruction, and adds subscribers who monitor the data. Once the data changes, receive To notification, update view

Step 3: Watcher subscribers are the communication bridge between Observer and Compile. The main things they do are:

Add yourself to the attribute subscriber (dep) when you instantiate yourself. You
must have an update() method. When
the attribute changes dep.notice() notification, you can call your own update() method and trigger the binding in Compile. If you call back, you will succeed.
Step 4: MVVM is the entrance to data binding. It integrates Observer, Compile and Watcher. Observer is used to monitor changes in model data, and Compile is used to parse and compile template instructions. Finally, Watcher is used to build up the relationship between Observer and Compile. Communication bridge to achieve the two-way binding effect of data change -> view update; view interactive change (input) -> data model change.

14 What kinds of attributes does vuex have

There are 5 types, namely state, getter, mutation, action, and module

15 What are the store features of vuex

  • Vuex is a warehouse, and there are many objects in the warehouse. The state is the storage location of the data source, corresponding to the data in the general vue object
  • The data stored in the state is responsive. The vue component reads the data from the store. If the data in the store changes, the components that rely on this data will also be updated
  • It maps the global state and getters to the computed calculated properties of the current component through mapState

16 What is the getter feature of vuex

  • The getter can perform calculation operations on the state, which is the calculation attribute of the store
  • Although calculated properties can also be done in components, getters can be reused between multiple pieces
  • If a state is only used in one component, it is not necessary to use getters

What is the mutation feature of 17vuex

  • Action is similar to muation, but the difference is: action submits a mutation instead of directly changing the state
  • action can contain any asynchronous operation

18 Should the ajax request code in vue be written in the methods of the component or in the action of vuex

If the requested data is not to be shared by other components, but only used in the requested component, it does not need to be placed in the vuex state

If it is reused by other places, please put the request into action to facilitate reuse, and wrap it into a promise to return

19 What are the problems without vuex?

  • Maintainability will decline, you have to modify the data, you have to maintain 3 places
  • The readability is reduced, because the data in a component, you can't tell where it comes from
  • Increasing coupling, a large number of uploads and distributions will greatly increase coupling. Originally, Vue used Component to reduce coupling, but now it is used in such a way that it is contrary to the original intention of componentization.

20 vuex principle

Vuex only exists as a plug-in of vue, unlike Redux, MobX and other libraries that can be applied to all frameworks, vuex can only be used on vue, to a large extent because it is highly dependent on vue’s computed dependency detection system and its Plug-in system,

The overall idea of ​​vuex was born in flux, but its implementation completely uses vue's own responsive design. Relying on monitoring and dependency collection belong to vue's proxy hijacking of the object's Property set get method. The last sentence ends the working principle of vuex. The store in vuex is essentially a hidden vue component without a template;

22 To use Vuex, you only need to execute Vue.use(Vuex) and pass in an example of a store object in the Vue configuration. How does store implement injection? Meituan

The Vue.use(Vuex) method executes the install method, which implements the encapsulation and injection of the init method of the Vue instance object, so that the passed store object is set to the store of the Vue context environment . Therefore, anywhere in V ue C omponent can pass this. store. Therefore, this can be passed anywhere in Vue Component.S T O R & lt E in . Because of this the V U E C O m P O n- E n- T any meaning the side are able to be pass through T H I S . Store access to the store.

23 state internally supports module configuration and module nesting, how to achieve it? Meituan

There is a makeLocalContext method in the store construction method. All modules will have a local context, which is matched according to the path during configuration. Therefore, when executing actions such as dispatch('submitOrder', payload), the local state of the module is obtained by default. If you want to access the state of the outermost or other modules, you can only access it step by step from the rootState following the path. .

24 When executing dispatch to trigger action (commit is the same), just pass in (type, payload), where did the first parameter store in the action execution function get it? Meituan

When the store is initialized, all configured actions, mutations and getters are encapsulated. When executing dispatch('submitOrder', payload), all processing methods whose type is submitOrder in actions are encapsulated. The first parameter is the current store object, so {dispatch, commit, state, rootState} and other data.

25 How does Vuex distinguish whether the state is modified directly from the outside or modified through the mutation method? Meituan

The only way to modify state in Vuex is to execute the commit('xx', payload) method. The bottom layer sets the _committing flag variable to true by executing this._withCommit(fn), and then the state can be modified. After the modification, the _committing variable needs to be restored. . Although the external modification can directly modify the state, it does not modify the _committing flag, so as long as you watch the state and judge whether the _committing value is true when the state changes, the legality of the modification can be judged.

26 How to realize the "space-time shuttle" function during debugging? Meituan

This feature is provided in devtoolPlugin. Because all state changes in dev mode will be recorded, the'space-time shuttle' function is actually to replace the current state with the state state at a certain moment in the record, using the store.replaceState(targetState) method to execute this._vm.state = state implementation.

27 What is axios? how to use? Describe the process of using it to implement the login function

axios is a module that requests background resources. npm i axios -S

If you are sending a cross-domain request, you need to configure it in the configuration file config/index.js

Guess you like

Origin blog.csdn.net/qq_40994735/article/details/108552264