The most complete front-end Vue interview questions in history

Time:2021-12-16
  1. Why cross domain?
    If a file from another source is not operated on, it will form a cross domain. Cross domain occurs when the protocol, domain name and port number of the requester are inconsistent with the protocol, domain name and port number of the server.
    Solution: install the plug-in
    Pip install django-cors-headers

  2. Vuex workflow?
    ① In the Vue component, you can use dispatch to start actions and submit the operation of modifying data.
    ② Then start the changes through the commit of actions to modify the data.
    ③ After receiving the commit request, changes will automatically modify the data in the state (data status in the data center) through change.
    ④ Finally, the store triggers the update of each component that calls it.

  3. What is vuex? How do you use it?
    Vuex is designed for Vue JS application development state management mode.
    Usage: store, getters, variations, actions, modules
    For details, please refer to:https://blog.csdn.net/qq_33226029/article/details/109628600?spm=1001.2014.3001.5502

  4. How to solve the problem that the data in vuex disappears after the page is refreshed?
    Use sessionstorage or localstorage to store data;
    You can also introduce the vuex persist plug-in

  5. How to prevent event bubbling and default behavior in Vue?
    When binding an event, a modifier is added after the instruction.stopTo stop bubbles,.preventTo block default behavior

  6. Deep copy and shallow copy?
    Suppose B copies A. when modifying a, check whether B changes:
    B changed is a shallow copy (modify the same value in heap memory), and unchanged is a deep copy (modify different values in heap memory).
    Shallow copy just adds a pointer to the existing memory address,
    Deep copy is to add a pointer and apply for a new memory, so that the added pointer points to the new memory.
    The most fundamental difference between deep copy and shallow copy is whether to really obtain the copied entity of an object rather than a reference.

  7. Vue life cycle?
    beforeCreate created beforeMount mounted beforeUpdate updated beforeDestroy destroyed
    actived deactived (keep-alive)Whether the component activates the call

  8. Keep alive: component cache
    https://juejin.cn/post/6844903624099758094

    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>
    

    router. JS:
    Meta: {keepalive: true} / / needs to be cached
    Hook execution sequence: created – > mounted – > active
    includeIndicates the page to be cached;excludeRepresents a page that does not need to be cached. If both are set at the same time,excludeIf the priority changes, the component is not cached.
    Application scenario:The user selects the filter criteria on a list page to filter out a data list, and then enters the data details page from the list page, and then returns to the list page. We hope that the list page can retain the user’s filter status.

  9. Vue value transfer method?
    props $emit() $on() $parent $children $listener $attr

  10. $on sibling component value transfer

    var event = new Vue(); //  Define an empty Vue instance
    A component: event$ emit('data-b', this.age);
    B component: event$ on('data-b', age=>{
        this.age = age;
    })

    $emitdistribute
    $onmonitor
    $offCancel listening
    $onceListen to one event at a time
    Define a central event bus bus in the JS file and expose it
    Specific implementation method:

    • Under utils, create an eventbus js
    // eventBus.js
    import Vue from 'vue';
    export default new Vue();
    
    • Introduce in components that need to be used
    import Bus from '@/untils/eventBus.js';
    //Method trigger
    handleBus(){
        Bus.$emit('tryBus');
    }
    
    //Method definition and Implementation
    Bus.$on('tryBus', ()=>{
        console. Log ('lit me ');
    });
    
    //If it is not used globally, remember to clear the method
    beforeDestroy(){
        Bus.$off('tryBus');
    }

    When using bus, destroy the bus in the beforedestroy function of the component receiving the bus, otherwise the method will be called all the time.
    Application scenario: “exit login” -> ① click exit login; ② Automatically log out after changing the password

  11. Component cross level value transfer
    $attrs a->b->c
    $listenersmonitor

    // a
    <parent :toCVal="val" @fromSon="chgVal"></parent>
    
    // b
    <child v-bind="$attrs" v-on="$listeners"></child>
    
    // c
    props:['toCVal'],
    this.$emit('fromSon');
    
  12. What are the Vue event modifiers?
    .stop .prevent .self .once .passive .sync

  13. This in the arrow function?
    It does not have this binding, but the function body can use this, which points to the this object in the lexical environment where the arrow function is currently located.

  14. What are the uses and differences between watch and computed in Vue?
    computed:
    Support caching. Only changes in dependent data will be recalculated;
    It does not support asynchrony and cannot monitor data changes;
    The default cache is based on responsive dependency, and is calculated through data declaration or props data;
    The attribute value is a function, and the get method is used by default; Data change method.
    watch:
    The listener does not support caching, and the data changes start directly;
    Support asynchronous;
    Receive two parameters, the new value and the old value;
    The listening data must be the data declared in data or passed in props by the parent component.

  15. Why does data in Vue component have to be a function?
    If it is not a function, the data of each component is the same address of memory. When one data changes, others also change. When it is a function, each component instance has its own scope. Each instance is independent of each other and will not affect each other.

  16. What is the difference between V-IF and v-show?
    V-IF is the creation and destruction of tags, and v-show is loaded only once during initialization. The cost of V-IF is relatively greater than that of v-show;
    V-IF is inert; V-show only does simple CSS switching.

  17. What is the difference between v-text and v-html?
    V-text is used for ordinary text and cannot parse HTML;
    V-html and vice versa.

  18. What is the role of V-for key?
    Use V-for to update the rendered data, which uses the “reuse in place” strategy by default. If the order of data items changes, Vue will not move DOM elements to match the change of data items, but simply reuse each element here and ensure that each element that has been rendered is displayed under a specific index. The key attribute type can only be string or number.
    The special attribute of key is mainly used in virtual DOM algorithm to identify vnods when comparing old and new nodes. If the key is not used, Vue will use an algorithm that minimizes dynamic elements and tries to repair / reuse elements of the same type as much as possible. It will rearrange the order of elements based on the change of key.

  19. What is SCSS? Installation steps in Vue cli? What are the major features?
    NPM download loader (SASS loader, CSS loader, node SASS). Configure the extensions attribute in webpack (add. SCSS extension). Vscope can be downloaded in extension;
    Properties: you can use variables, you can use mixers, you can nest, etc.

  20. Vue get DOM?
    ref

  21. Vue initialization page flashing problem?
    webpack、vue-router
    v-cloak css:[v-cloak]:display:none

  22. What is Vue router?
    Vue router is the official routing manager.
    Main functions: route nesting, modularization, component-based route configuration, route parameters, query, wildcard, fine-grained navigation control, custom scroll bar behavior, etc.

  23. Vue routing parameters, receive?
    Transmission:this.$router.push({path:'', query(params):{}})
    Connection:this.$router.query.xxx

  24. Anti shake and throttling?
    Throttling is a function that is executed once within a certain period of time, which is mostly used for scroll events;
    Anti shake is a function that executes the last time in a certain period of time. It is mostly used in input operation, form submission, etc.

  25. How to make SCSS work only in the current component?
    <style scoped>

  26. vue observable?
    Similar to vuex data sharing

  27. Destructuring assignment

    //Exchange the values of two variables
    var val1 = 5;
    var val2 = 10;
    
    //General create temporary variable temp
    var temp = val1;
    tal1 = tal2;
    tal2 = temp;
    
    //Using deconstruction assignment
    [val1, val2] = [val2, val1];
  28. Differences between route push and replace

    this.$ router. push('home'); //  Jumping to the home page will add a new record to history
    this.$ router. replace('home'); //  Generally, replace is used for 404 pages, and new records will not be added to history
  29. Array. From () is used to convert two types of objects into real arrays

    let obj=[{id:5, a:7}]
    Array.from(obj)
    
  30. Array. Of() is used to convert a set of values into an array

    Array.of(1,2,3) // [1,2,3]
    
  31. Find() and findindex() of array instances

    [1,2,-5,10].find(n => n<0) // -5
    [1,5,10,15].findIndex((val, i, arr) => {
      return val>9
    }) // 2
    
  32. Array instance fill()

    [1,2,3].fill(7) // [7, 7, 7]
    ['a','b','c'].fill(7,1,2) // ["a", 7, "c"]
    
  33. Array instance includes()
    This method returns a Boolean value indicating whether an array contains the given value, similar to the includes () of the string

    [1,2,3].includes(2) // true
    [1,2,3].includes(4) // false
    [1,2,3].includes(3,2) // true
    

    string.includes(searchvalue, start)
    searchvalueRequired, the string to find.
    startOptional. It is set to search from that location. The default value is 0.

  34. Array de duplication method

    var arr = ['1','2','3','4','4','6','2'];
    const newL = [];
    for(const o of arr) {
        if (newL.find(c=>c=== o)) {
            continue;
        }
        newL.push(o);
    }
    

    (1) Set

    let el = new Set(arr)
    

    (2) indexOf

    let el1=[];
    arr.forEach(item => {
        if(el1.indexOf(item) === -1){
            el1.push(item)
        }
    })
    

    (3) filter

     let arr2 = arr.filter((x, index,self) => {
        return self.indexOf(x)===index;
     }); 
    
  35. Convert string array to number array

    ['1','2','3'].map(Number) //  [1, 2, 3]
    
  36. for… In return key list
    for… List of values for the of numeric property
    For a more detailed explanation, see:https://blog.csdn.net/qq_33226029/article/details/111179890?spm=1001.2014.3001.5502

  37. closure
    It is often used to “indirectly access a variable”. In other words, “hide a variable”, variables outside the function can be used inside JS functions.
    Functions defined inside functions;
    Anonymous functions create closures;
    A bridge connecting the inside and outside of a function. The inner function can use all variables of the outer function. Even if the outer function has been executed, the closure function can be used to imitate the scope, etc.
    Application scenario: setTimeout
    The first function passed by setTimeout cannot take parameters, i.e

    setTimeout(func(param),1000)
    function func(param){
      return function(){
        alert(1)
      }
    }
    var f = func(1)
    setTimeout(f,1000)
    
  38. Memory leak
    Memory leak means that variables that you can’t use (access) still occupy memory space and can’t be used again.

  39. The map type is also calledSimple mapping
    Function: save a group of key value pairs. Saving key value pairs with ordinary objects will easily confuse keys with native attributes. Simple mapping can separate keys and values from object attributes, so as to ensure the safe storage of object attributes.

    var map = new Map();
    map.set('name','pp');
    map.set('book','js');
    console.log(map.has('name')); // true
    console.log(map.get('name')); // "pp"
    map.delete('name');
    

    Related to simple mapping isSet type。 A collection is a set of non repeating elements. There are only keys in the collection and no values associated with keys.
    To add elements to the collection, use the add () method,
    Check whether the element exists. To use the has () method,
    Delete element delete() method.

    var set = new Set();
    set.add('name');
    console.log(set.has('name')); // true
    set.delete('name');
    console.log(set.has('name')); // false
    
  40. To JSON object parse()
    Convert to string JSON stringify()

  41. Object. Assign() object merge

    const target = {a:1, b:2};
    const source = {b:4, c:5};
    const returnTarget = Object.assign(target, source);
    console.log(returnTarget); // {a: 1, b: 4, c: 5}
    
  42. Router link: package a label
    Router view: render route view

  43. CSS isolation scheme

    • BEM (block element modifier) convention front end prefix
    • CSS modules generate non conflicting selector names when packaging
    • Shawdow DOM
    • css-in-js
  44. What’s the difference between less and sass?
    Less: use@Define variables
    SCSS: use$Define variables; It can be judged that the statement if else can loop for

  45. Why can const change objects and arrays?
    Const only ensures that the pointer does not change, and modifying the object property will not change the pointer of the object, so it is allowed.
    Reference type: reference address. It only saves the pointer to the actual data.
    Basic type: the address is fixed, and the value exists at the memory address pointed to by the variable.
    Const is used to define constants, which must be initialized during definition and cannot be changed after definition.

  46. v-deep
    If you do not use the scoped attribute to change the style of public components, it will be polluted to the whole world, but if you set the scoped attribute, directly overriding the style will not take effect.
    The third-party component library is used in Vue components. You need to customize the style in this component without affecting the style of the third-party component used elsewhere.
    With the deep selector, you can penetrate the scoped without polluting the global style.

    //SCSS / deep / a warning will occur
    ::v-deep.el-btn-small{}
    
    // css
    .a>>> .b{}

Don’t go. There’s follow-up······
This article is just my personal knowledge points sorting, which will be continuously supplemented in the future. If the knowledge points encountered in work are not recorded in time, they are likely to be forgotten. If you can think of other Vue front-end interview questions, please leave a message in the comment area. Sharing is a virtue. Thank you for your contribution.

PS: writing is not easy. If you want to reprint, please indicate the reprint source.