CSS related

What are the new features of CSS3

Css3 has a lot more features for mobile than CSS2

  • Rounded corners: border – the radius
  • Box shadow: box-shadow
  • Animation: Transition,transform,animation, etc

How to center a Div vertically (at least 3 ways)

  • Location:
    • The first way to think about it is by setting absolute positioning to the div and**left,right,top,bottom**Set to**0,margin:auto**It can be centered horizontally or vertically
    • The second way to think about it: by setting absolute positioning to div,**left = 50%,top = 50%**Set div to be half of itself to the left:**margin-left: 2,margin-top: 2. * *
    • The third way to think about this is to set the absolute position of the div, left 50%,top 50%, and div half of itself across the left and up:**transform:translate3d(-50%,-50%,0)**
  • Flex layout:
    • There are two divs, a parent div and a child divdisplay:flexAnd set the horizontal center of the parent divjustify-content:centerAnd set the parent div to be vertically centeredalign-items:centerCan be

What problem does ClearFix solve?

  • There are many ways to solve this, but the main goal is to make the parent element have height
    • Sets absolute positioning for the parent element* * : position: absolute * *
    • Set to the parent element**overflow:hidden; 六四运动
    • It’s done by pseudo-objects
 .clearfix:after {
     content: "";
    display: block;
    clear: both;
    height: 0; 
  }
Copy the code

Understanding of box models (including IE and W3C standard box models)

The box model is essentially a box in which the browser views each tag as an image. Each box (i.e., tag) has a width, a border, a gap between the content and the border (i.e., the padding), and a margin between the boxes.

The graph is shown as:



  • Of course, the box model includes two kinds: IE box model and W3C standard box model
    • Width =border+padding+ content width
    • Total width of standard box model = border+padding+width
  • Box-sizing :border-box; box-sizing:border-box; box-sizing:border-box
    • Box-sizing: border-box // box-sizing: border-box
    • Box-sizing: content-box // W3c box model

CSS 3 animation:

Oh, you asked cSS3 animation ah, CSS3 animation generally includes two kinds

The difference between REM and EM

  • Both REM and EM are relative units with different main reference labels
    • Rem is implemented relative to the root size, i.e. font size relative to the label. The default browser size is font size:16px
    • Em: the size of the tag relative to the parent element. Like %, % is also relative to the parent, but % is relative to the width of the parent element, and em is relative to the size of the parent element

How to do the adaptation of the mobile terminal

There is no best method for front-end adaptation, only suitable method. At present, the main methods for front-end adaptation are: — percentage, EM, REM, media Query, Flex layout (elastic box), VW, VH, etc

  • So far I use rem, Flex layouts a lot on my projects, and sometimes media queries, when doing PC responsive layouts
  • The main use of a hand-washed JS library flexible. Js, when the page changes, detect the width of the page, divided by 10, dynamically assigned to the font-size. Properties. The layout of the page is carried out through REM, so it can be adapted to all mobile devices

What about VW and VH

  • Vw and VH are CSS layout units that have been slowly gaining popularity in the last 2 years and are now being used by some companies,
  • Vw and VH relative to screen width and screen height, 1VW equals 1% of screen width, 100VW equals 100% of full screen width,
  • Vh is similar to VH but relative to the screen height, with 1Vh equal to 1% of the screen height and 100Vh equal to 100% of the full screen height

Cookie,localStorage and sessionStorage

  • Cookie can set the expiration time, but does not have its own access to the method, needs to be encapsulated, each request to follow the request sent, while localStorage and sessionStorage can have their own access methods such as:
    • setItem()
    • getItem()
    • removeItem()
    • **clear() **

  1. autio,video
  2. H5 provides audio and video components, can achieve video playback, I used to use it to do music player, but for a long time no use, there are play,pause and access to the current time and total time method, have a look at the AUDIO,video API, I can use quickly
  3. other

Compatibility correlation

  1. PC
    1. Generally, it is an IE compatibility problem, such as: use CSS hack to solve *, _, etc
    2. JS has feature matching to determine whether a JS method exists
  2. Mobile: I have encountered 300ms delay and spot-through problems in mobile terminal, which can be solved by fastClick plug-in
  3. Performance optimization is a big topic: there are many aspects of optimization,
    1. Network loading optimizations: for example, reduced HTTP requests (merging files, CSS Sprite charts, lazy image loading), reduced DOM operations (DOM caching), code encapsulation,
    2. Third-party library CDN loading, gZIP compression and so on

How does Internet Explorer 8 support semantic tags

A library HTML5shiv. Js, directly into ok, you can baidu under this file, the principle is to translate the semantic tags in the low version of the browser into block level elements, so that the browser can parse

Correlation of common algorithms

Sort an array

Bubble sort: Take one digit from an array and compare it to the next. If you want to sort from smallest to largest, put the smaller digit in front and the larger digit in back. Simply switch the positions of the two digits.

 var arr=[3.1.4.2.5.21.6.15.63]
  function sortA(arr){
   for(var i = 0; i<arr.length-1; i++){
      for(var j=i+1; j<arr.length; j++){// Get the first value and the next value to compare
          var cur=arr[i]
          if(cur>arr[j]){
              // Since we need to exchange values, we will replace the latter value, and we will save it fresh
           let index=arr[j]
          / / exchange value
          arr[j]=cur
          arr[i]=index
          }
      }
   }
   return arr;
  }

// Since only one maximum value can be exchanged at a time, we need to set up a layer of for loops
Copy the code

Array to heavy

For example: […newSet(arr)]

function unique(arr){
  var newArr = [];
  var temp = {};var item;
  for ( var i = o, len = arr.length; i < len; i++){
    item = arr[i];
    if(! temp[item] ){ temp[item] =true; newArr.push(item) ; }}return newArr;
}
Copy the code

The address bar resolves into an object

Object deep copy, shallow copy cleavage

Shallow copy of an object means that changing the property value of one object also changes the property value of another object, which means mutual influence. Deep copy of an object means that changing the property value of one object does not change the property value of another object. You can implement deep copy of an object by using various methods

  • throughJSON. Stringify and JSON. The parseTo implement the
 var obj={name: '1610 a'}var obj2=JSON.parse(JSON.stringify(obj))
Copy the code
  • It’s done recursively

  • Take a look at the code, function compatibility handling, and encapsulation
var EventUtil={
	
   addHandler:function(element,type,handler){ // Add events
      if(element.addEventListener){ 
         element.addEventListener(type,handler,false);  // Add events using the DOM2 level method
      }else if(element.attachEvent){                    // Add events using the IE method
         element.attachEvent("on"+type,handler);
      }else{
         element["on"+type]=handler;          // Add events using the DOM0 level method}},removeHandler:function(element,type,handler){  // Cancel the event
      if(element.removeEventListener){
         element.removeEventListener(type,handler,false);
      }else if(element.detachEvent){
         element.detachEvent("on"+type,handler);
      }else{
         element["on"+type]=null; }},getEvent:function(event){  // Use this method to retrieve the Event object across browsers
      returnevent? event:window.event;
   },
	
   getTarget:function(event){  // Return the actual target of the event
      return event.target||event.srcElement;
   },
	
   preventDefault:function(event){   // Prevent the default behavior of events
      if(event.preventDefault){
         event.preventDefault(); 
      }else{
         event.returnValue=false; }},stopPropagation:function(event){  // Stop event propagation in the DOM immediately
                                     // Avoid triggering event handlers registered with document.body
      if(event.stopPropagation){
         event.stopPropagation();
      }else{
         event.cancelBubble=true; }}}Copy the code

Js related

closure

How to understand the prototype chain in JS?

  1. What prototype? Prototype chain
  • Prototype:

  • In JS, everything is an object, and each object has its own properties
  • How can multiple objects share one or more methods in js? Prototypes are designed to solve this problem. Every object in JS has an object associated with it, called a prototype object
  • Every time an object property is obtained, it is a query process. If an object’s own property cannot be found, it will look for its prototype object
  • The prototype chain:

  • The prototype is connected into a chain. In the process of looking for attributes, js will go to the prototype object if it can not be found in its own attributes. If it can not be found in the prototype object, it will go back to the prototype object to find, that is, according to the prototype chain to find until the top of the prototype chainObject
  1. What does it do? How does it work



  1. The advantages and disadvantages
  • Benefits of prototype chain inheritance
    • Only the properties of the superclass constructor are inheritedInherits the properties of the parent stereotype
    • Shortcomings 1, 2 and 3 of prototype chain inheritance are solved
    • Multiple constructor attributes can be inherited (Call multiple)
    • Arguments can be passed to a parent instance in a child instance
  • Disadvantages of prototype chain inheritance
    • Only properties of the superclass constructor can be inherited
    • There is no way to reuse the constructor (re-call each time you use it)
    • Each new instance has a copy of the superclass constructor, bloated

JS inheritance (ES6 included) — or if you ask: there are two classes A and B, how can B inherit from A?

  1. What is Inheritance: an official concept
    1. Js inherits es6 inheritance by [somehow] allowing one object to access properties and methods in another object
  2. What good is inheritance

How to implement inheritance: Constructor inherits prototype inherits copy inheritance

Stereotype inheritance: make the stereotype of the new instance equal to the instance of the superclass

/ / parent class
function Person(name){    // Add arguments to the constructor
    this.name=name;
    this.sum=function(){
        alert(this.name)
    }
}
// Adds prototype properties to the constructor
Person.prototype.age = 10

// Prototype chain inheritance
function Per(){
    this.name='ker';
}
Per.prototype=new Person(); / / the main
var per1=new Per();
console.log(per1.age);   // Print the result: 10
// Instanceof determines whether an element is on another element's prototype chain
// Per1 inherits the property of Person and returns true
console.log(per1 instanceof Person);  // Print the result: true
Copy the code
  • ** Attributes that can be inherited from an instance include: instance constructor attributes, superclass constructor attributes, and superclass prototype attributes.
  • Disadvantages:
    • A new instance cannot ask a parent to construct an ominous parameter.
    • Single inheritance.
    • All new instances share the properties of the parent instance. (The properties of stereotypes are shared, so if one instance changes the properties of the stereotype, the other instance changes the properties of the stereotype as well!)


1, 2, 3 - can inherit multiple constructor attributes (call multiple) - can pass arguments to parent instances in child instances - ** Disadvantages: ** - Only properties of the superclass constructor can be inherited. - Constructor reuse is not possible. Each new instance has a copy of the superclass constructor, bloated. <br /> <a name="lEAta"></a> ### ES6 inheritance is a relatively new and mainstream way to define a class with 'class', an extends class with 'super', and a superclass with 'super()'. Class A{constructor(){// constructor(); } // constructor extends A class B {constructor(){super()} // constructor extends A class B {constructor(){super()} // constructor extends A class B {constructor(){super()} // constructor extends A class B {constructor(){super() } // instantiate class B: var b1=new B() console.log(b1); // b1. Method 1Copy the code

How to bind JS native events

A: There are three main types of JS native binding events:

  1. HTML event handler
  2. Dom0-level event handler
  3. Dom2-level event handler
  • HTML eventIt is not used anymore. It is to add events directly to various HTML tags, similar to CSS inline style. The disadvantage is that it is not easy to maintain, because it is scattered in the tags, that is, it is too coupled
<button onclick="Event Handler">Am I</button>
Copy the code
  • DOM0 level eventsAt present, more binding events are used on the PC side, and the compatibility is good. The main method is to get the DOM element first, and then directly add events to the DOM element
var btn = document.getElementById('id elements')
      btn.onclick = function() {
         // Event logic to be processed} How to remove DOM0 event? It's simple: btn.onclick=null; Leave it blank. Advantages: Good compatibility Disadvantages: Only supports bubbling, does not support captureCopy the code


  • Grade DOM2 events, mobile terminal is used more, but also has many advantages, providing specialized binding and removal
var btn=document.getElementById('id elements')
// Bind the event
 btn.addEventListener('click', the name of the bound event handler,false)
 // Remove events
 btn.removeEventListener('click', the name of the event handler to remove,false)
Copy the code

JS native common DOM operation methods?

  • Js native DOM operation methods have?
  • To find the
    • getElementByid
    • getElementsByTagName
    • querySelector
    • querySelectorAll
  • insert:appendChild,insertBefore
  • delete:removeChild
  • cloning:cloneNode
  • Sets and gets properties:SetAttribute (" attribute name ", "value"),getAttibute(" attribute name ")

New features in ES6?

What are the JS design patterns (singleton pattern observer pattern etc.)

There are many JS design patterns, but the one I know is the singleton pattern, the observer pattern

  • Singleton mode:
    • To ensure that there is only one instance of a class, the implementation method is generally to determine whether the instance exists, if there is directly return, if not created and return, this ensures that a class has only one instance object. In JavaScript, a singleton acts as a namespace provider, providing a unique point of access to an object from the global namespace.
  • Observer mode:
    • The use of the observer is:
    • The observer mode should be considered when a change in one object requires that other objects be changed at the same time, and it does not know how many objects need to be changed.
  • In general, what the observer pattern does is decouple, making both sides of the coupling dependent on abstractions rather than concrete ones. So that changes on one side don’t affect changes on the other

Understanding of JS interviewees

What is object orientation: abstracting what you need to do into an “object” and then calling that object over and over to do what you want

  1. Object oriented usage: Object creation
<script>
  var box = new Object(a)// Create an Object
  box.name='Object Oriented Usage'  // Create a name attribute and assign it to it
  box.age = 100  // Create an age attribute and assign it to it
  // Create a run () method and return a value
box.run=function(){
 return this.name + this.age +  'Running' 
}
  alert(box.run())  // Output the values of the properties and methods
  console.log(box.run()); // Printout: Object-oriented usage 100 running
</script>
Copy the code
  • Cons: Creating multiple similar objects can create a lot of code
  1. The factory pattern creates objects
 // Integrate instantiated functions
  function createObject(name,age){
   var obj = new Object()
   obj.name = name
   obj.age = age
   obj.run=function(){
       return this.name + this.age +'In operation... '
   }
   return obj
  }
  var box1=createObject('less'.100)  // The first implementation
  var box2=createObject('jack'.200)  // The second implementation
  console.log(box1.run());  // Printout: Less100 running...
  console.log(box2.run());  // Printout: jack200 running...
  // alert(box2.run()) // Remain independent
Copy the code
  • The factory pattern solves the problem of repeated instantiation
  • Disadvantages:
    • Creating different objects where properties and methods are created repeatedly consumes memory; There are function identification issues and so on.
  1. **Var obj = {}
// The constructor method creates the object
  function box(name,age){
      this.name=name
      this.age=age
      this.run = function(){
          this.name+this.age+'In operation... '}}var box1=new box('less'.100) / / new box ()
  var box2=new box('jack'.300)
  alert(box1.run()); //undefined 
  alert(box1 instanceof box);  // It is clear that it belongs to box and prints: true
Copy the code
  • When constructors are used and the new constructor () is used, then new Object () is executed in the background.
  • The scope of the constructor is given to the new object(that is, the object created by new object()), and this in the body of the function represents the object created by new object().
  • Execute the code inside the constructor
  • Return new object (background return directly)

The prototype

Inheritance: Talk about object orientation in ES6

ES6 has a keyword, Class, to define classes

class User{
    / / the constructor
    constructor(name,age){
        this.name=name
        this.age=age
    }
    // Define class methods
    showName(){
        console.log(this.name); }}let user = new User('rest'.21)
console.log(user.showName());  // The print digit is undefined
Copy the code
  • Classes in ES6 have specialized constructorsconstructorThe constructor is separated from the class, and the method is defined: there is no need to define the prototype, and the method is defined directly in the class
  • Es6 declares the methods of classes
let Example1=class{
      constructor(a){
          this.a=a
          console.log(a); }}let ex1=new Example1(1)

  / / naming classes
  let Example2=class Example2{
      constructor(a){
          this.a=a
          console.log(a); }}let ex2=new Example1(2)
  / / the class declaration
  class Example{
      // Class body content
      constructor(a,b){
          this.a=a
          this.b=b
      }
  }
Copy the code

JS array common methods (at least 6)

  • Common methods for JS array are:
    • push,
    • pop,
    • unshift
    • shift
    • splice
    • join
    • concat
    • forEach
    • filter
    • map
    • sort
    • some
    • Every (etc.)
  • But are usually in the development of a very common method, we can add a little ES6

What are the differences between the built-in traversal methods of the JS array

** forEach:** This method is intended to replace the for loop that iterates through the array and return undefined

let arrInfo=[4.6.6.8.5.7.87]
 let as = arrInfo.forEach((item,index,arr) = >{ 
    // For example, return an array with each item value greater than 9
    return item>9
})
console.log(arrInfo); // Print the result: undefined
Copy the code
  • Among them:
    • For each item that the item code traverses,
    • Index: represents the index of each item traversed,
    • Arr stands for the array itself
  • Filter: * * * * is aFiltering traversalReturns a new array that satisfies the condition true if it returns true
let arrInfo=[4.5.6.6.8.9.7.98]
let resultARR = arrInfo.filter((item,index,arr) = >{ 
    // For example, return an array with each item value greater than 9
    return item>9
})
console.log(resultARR); // Print the result: 9
Copy the code
  • Map: * * * * the map method is mainly used in an array of complex logic to handle more, especially the react traversal data, is also frequently used, writing and similar forEach
  • **some:** This method returns true as long as there is at least one result in the array that satisfies the condition, otherwise returns fasel, and writes like forEach
  • **every:** This method returns true if every item in the array satisfies the condition, and false otherwise. It is written like forEach

JS scope and scope chains

JS scope is the scope that JS identifies variables, and scope chain is the order in which JS finds variables. First, let’s talk about scope. JS scope mainly includes global scope, local scope and block-level scope of ES6

  • Global scope: the scope of variables defined in window and accessible anywhere
  • Local scope: is the scope of variables defined only within a function
  • Block-level scopeIn simple terms, variables defined in any code block with let and const are considered to be block-scoped variables
    • For example, variables defined by let in a for loop, variables defined by let in an if statement, and so on
    • Note: do not use global variables as far as possible, because it is easy to cause global pollution, name conflicts, to find bugs
  • The so-called scope chain is the process of finding variables from the innermost scope to the outermost scope. The resulting chain is the chain of scope

What happens between entering the URL and when the page loads?

It goes something like this:

  1. The DNS
  2. A TCP connection
  3. Sending an HTTP request
  4. The server processes the request and returns the required data
  5. The browser parses the rendered page
  6. Connect the end of the

Enter a domain name, the domain name to find the server address (IP) corresponding to the domain name through DNS resolution, through TCP request link service, through the WEB server (Apache) return data, browser based on the returned data to build the DOM tree, through the CSS rendering engine and JS parsing engine to render the page, close the TCP connection

What is JS event agent (also called event delegate) and how it is implemented?

The JS event proxy works by binding events to parent elements (e.g. Ul) and not to child elements (e.g. Ul). Li) binding event, then when you click the child elements, through the event bubbling mechanism on the binding of the parent element trigger event handler, the main purpose is to improve performance, because I don’t have to give each child element binding events, to the parent element binding only once, in native js is by targe attribute of the event object

var ul = document.querySelector("ul");
	ul.onclick = function(e){   //e refers to the event object
	var target = e.target || e.srcElement; //target gets the target that triggers the event (li)
		if(target.nodeName.toLowerCase() == 'li') {// The target (li) node name is changed to lowercase letters. Otherwise, it is changed to uppercase letters
			alert(target.innerHTML)
		}
	}
Copy the code

$(‘ul’).on(“click”,”li”,function(){// event logic}) the second argument refers to the specific target of the event. This is especially useful for binding events to dynamically added elements

What are the JS data types?

  • Basic data types:
    • number
    • string
    • Boolean
    • null
    • undefined
    • Symbol (ES6 added)
  • Compound types:
    • Object
    • function

The call, the apply, bind the difference

Call,apply,bind (),bind (

  • The main difference between Call and apply is that the parameters passed after call are separated by commas
  • The arguments passed by apply are of the Array form. The arguments passed by apply start with A, so they should be of the Array form.
  • Bind returns a function, followed by parentheses if it is to be executed
    • Such as:Bind (obj, 1, 2,)(),bind can be separated only by commas and cannot be an array
  • Hand bind case:
function bind_1(asThis, ... args) {
  const that = this; 
   // this is the fn call to bind
  function handle(. args2) {
   returnthat.apply(asThis, ... args, ... args2) }; handle.prototype= that.prototypereturn handle
}
Copy the code

git

  1. How are projects managed in your company?
    1. The main way to version control projects is through Git
  2. What are some common Git commands?
    • git add .
    • git status
    • Git commit -m ‘initialize’
    • git push
    • The git pull etc.
  3. How to resolve conflicts when multiple people are working on the same file?
    • When conflicts occur when multiple people collaborate to modify the same file, I first git pull down the remote file, manually modify the conflicting code, and thengit add ,git commit,git pushAnd then upload it to the remote repository. If you can’t pull it, you can stash it with git Stash, then pull it, and thengit stash pop, take out the original written, manually modify, and then commit

How does Ajax relate to data interaction with the back end

I interact with the backend through Ajax and implement efficient development of the front and back ends through unified interface documents. If the interface documents cannot be specified in detail or the parameters in the interface documents cannot provide data, I will take the initiative to communicate with the back-end engineers until the business development related to the interface is completed. Of course, to verify some of the interface issues, there are auxiliary tools, such as runAPI, an online testing tool

How do you work if the back-end data interface is not ready

If the backend interface is not ready to, I will communicate with the back-end engineer, the format of the data returned by setting interface, and then the front through some mock data tools (the last company is using a easymock, thief simple) to mass produce false data, can let the front-end and back-end development at the same time, without having to wait for the back-end data interface to write good development again, This improves the overall development efficiency of the project

Describe your understanding of ajax’s same origin policy

The Same Origin policy, a well-known security policy introduced by Netscape, is now used by all javascript enabled browsers. Originally, it means that the Cookie set by page A cannot be opened by page B unless the two pages are “identical”. “Homologous” means “three identical”.

Ajax same origin policy is for security reasons. Ajax does not allow access to resources under different domain names.

Describe when cross-domain solutions are generated and how they are implemented.

Cross-domain access occurs in the following cases: Different protocols, different domain names, different ports, and different domain names and IP addresses.

Cross-domain solutions There are three mainstream solutions

Native Ajax interaction processes (i.e., processes)

  • The interaction process
    • First createXHR objectnamelyXMLHttpRequest()
    • And then open is ready to send, and open has three parameters
      • One is the way of submissionThe get and post,
      • The second is the interface address.
      • The third is synchronous and asynchronous
    • The third step is to send
    • Step 4 re-send the process through**onreadystatechange**To listen for incoming callback functions**readyState = = 4 and status= = 200**To determine whether the return was successful, and then pass**responseText**The data is received successfully

Your understanding of synchronous and asynchronous

Sync, or sync, literally means that code is executed line by line, and subsequent code and requests are not executed until the previous code and request have been executed

How to solve ajax caching

By adding a random number (also known as file fingerprint) to the end of the file name, the main principle is that the browser will first check whether the file URL requested for the second time has been cached in the browser. If it has been cached, it will use it; otherwise, if it is a new file URL, it will request again from the server

JavaScript native,jQuery, Vue,react, small program Ajax and background interaction with what technology

  • JavaScript native Ajax:
    • Using aXMLHttpRequestobject
  • In the jQuery Ajax:
    • $.ajax()
    • $.getJSON()
    • $.get()
    • $.post (), etc
  • Ajax in the vue:
    • Vue-resource (in vue1.x)
    • Axios (mainstream)
  • Wechat small program Ajax: with the small program built in
    • Wx. Request () method
    • Query $.ajax() is similar, parameter URL,success, data,method,fail, etc

The HTTP status code

Was your last company’s project a front-end separation?

Yes, it was a separate back and front end project, but it wasn’t written in the beginning, it was written in a mixed back and front end code, and then it was reconstructed as separate back and front end code, so that the front end and the back end could maintain their own code

  • Note: The so-called separation of the front and back ends means that the responsibilities of the front and back ends are clear:
  • The backend only provides the data interface address to return JSON data,
  • The front-end uses Ajax to request JSON data, and all the business logic of the page is written on the front-end, so that the front-end control is stronger and the back-end logic processing pressure is reduced.

Deep copy, shallow copy

  • Use es6Object.assign({},{})Do object merge, if it’s an array you can use ES6Array.from, or es6’s extension operator. arr
  • If you use ES5, you need to loop for shallow copy, and if you use deep copy, you need to recurse. Of course you can use it* * JSON. Parse (JSON. Stringify (object)) * *To implement deep copy

Vue related

What is the biggest feature of VUE or what is the core of VUE

Vue commonly used basic instructions which

  1. V-if: Render elements based on the true or false condition of the expression’s value. The element and its data binding/component are destroyed and rebuilt during the switch.
  2. V-show: Toggles the display CSS property of an element based on the true or false value of the expression.
  3. V-for: loop instruction that renders a list based on an array or object. Vue 2.0 and above must be used with a key.
  4. V-bind: Dynamically bind one or more features, or a component prop, to an expression.
  5. V-on: Used to listen for DOM events, such as click events, on a specified element. Bind event listeners.
  6. V-model: Implements bidirectional binding between form input and application state
  7. V-pre: Skip the compilation of this element and its children. Can be used to display the original Mustache tag. Skipping a large number of nodes without instructions speeds up compilation.
  8. V-once: Render elements and components only once. In subsequent re-rendering, the element/component and all of its children are treated as static content and skipped. This can be used to optimize update performance.

A common modifier for Vue

  • The v-ON directive uses the following modifiers:
    • .stop– callevent.stopPropagation(), disable event bubbling.
    • .prevent– callevent.preventDefault(), to prevent the default behavior of events.
    • .capture – Use capture mode to add event listeners.
    • .self – The callback is fired only if the event is fired from the element itself to which the listener is bound.
    • . {keyCode | keyAlias} – only events from the specific trigger callback key trigger.
    • Native – Listens for native events on the component root element.
    • .once – Triggers only one callback.
    • .left – (2.2.0) Is triggered only when the left mouse button is clicked.
    • .right – (2.2.0) is triggered only when the right mouse button is clicked.
    • .middle – (2.2.0) Is triggered only when the middle mouse button is clicked.
    • .passive– (2.3.0) { passive: true }Mode to add listeners
  • Note: If you are wrapping your own component or using a third-party UI library, you may find that this does not work, so you need to use the ‘·. Native modifier.
< span style =" box-sizing: border-box! Important; word-wrap: break-word! Important; "style =" box-sizing: border-box! Important;"Copy the code
  • A common modifier used by the V-bind directive

Prop – is used to bind DOM properties.

  • Camel – (2.1.0+) converts the Kebab-Case feature name to camelCase
  • **sync **(2.3.0+) syntax sugar, which extends to a V-on listener that updates the parent binding value
  • The V-model directive is a common modifier
    • Lazy-listens for the change event instead of input
    • Number – Converts the input string to a number
    • Trim – Enter the first and last space filter

Why must data in Vue be a function

<script> export default {data() {// return a unique object. Do not share an object with other components. Return {menu: MENU.data, poi: POILIST.data } } } </script>Copy the code

Since components can be shared, but their data is private, each component should return a new data object, returning a unique object instead of sharing an object with other components

The difference between v-if and V-show

  • Both V-if and V-show can show and hide an element, but there are essential differences
    • V-if is lazy. If the value is false, the element will not be loaded. If the value is true, the element will be loaded dynamically
    • V-show: yes The corresponding HTML code is loaded whether the value is true or false. If the value is false, display:none is used to hide the HTML code from the page. If the value is true, display:block is used to display the HTML code on the page
  • Application scenarios: V-show is used in frequent switching cases, and V-if is used in infrequent switching cases

How to implement vue custom instruction and applicable scenarios

  • Vue in addition to v-for, V-if and other built-in VUE instructions, but can not meet all the development needs, sometimes need custom instructions, custom instructions to create global custom instructions and local custom instructions
  • Global custom directives:**Vue.directive(' directive name ',{el) {}})**
  • Local custom instruction:**directives:{ }**

What does vue filter do (vuE1.x vs. vuE2.x)

The VUE filter is used to format the rendered data.

For example: the gender of the data returned in the background is 0 and 1, but the rendering to the page can not be 0 and 1, I have to convert to “male” and “female”, then the filter will be used, and the commodity price read out is a common value, such as: 230035, but I want to add a currency symbol and thousands of cents in front of it, such as: How to create a filter? Similar to creating a custom directive, there are also global and local filter forms

  • Global filter
Vue.filter(' filter name ',function(parameter1, the parameter2,...) {

      / /...... .
      returnFormat of data to return})Copy the code
  • Local filters: Add the filters attribute inside the component to define the filters
Fitlers :{filter name (parameter)1, the parameter2,,... Parameters n) {/ /...... .
      returnFormat of data to be returned}}Copy the code

What are the vUE lifecycle hook functions, and when do they fire

  • The vUE life cycle is a complete cycle of a component from birth to death, including the followingFour phases: create, mount, update, destroy
    • Before creating:beforeCreate, after creation:created
    • Mount the front:beforeMount,After the mount:mounted
    • Before the update:beforeUpdate, after the update:updated
    • Before destruction:beforeDestroy, after destruction:destroyed
  • I usually use more hook isCreated and Mounted, createdMounted is used to perform DOM operations and initialize plug-ins after the DOM is mounted.beforeDestroyThe user clears timers and unbinds events
  • Also added is the use of the built-in keep-alive component to cache instances instead of constantly creating and destroying them (which is expensive)
    • Actived instance is activated
    • Deactived instance is invalid
  • The following is the detailed version, we understand ok:
  • Lifecycle hook functions (11)The one marked blue means belong to type.
    • BeforeCreateFunction is called after instance initialization and before data Observer and Event /watcher event configuration.
    • Created Function is called immediately after the instance is created. At this stage, the instance has completed the following configuration: Data Observer, operation of properties and methods, and watch/ Event event callback. However, the mount phase has not yet started and the $EL attribute is not currently visible.
    • BeforeMount Function is called before the mount begins: the related render Function is called for the first time.
    • Mounted Function EL is replaced by the newly created Vm. el and called after the instance is mounted. If the root instance mounts a document element, vm.el is replaced when Mounted is called, and the hook is called after mounted to the instance. If the root instance mounts a document element, vm.el is replaced when Mounted is called, and the hook is called after mounted to the instance. If the root instance mounts an element in the document, vm.el is also in the document when Mounted is called.
    • BeforeUpdateFunction Is called when data is updated and occurs before the virtual DOM is patched. This is a good place to access an existing DOM prior to an update, such as manually removing an added event listener. This hook is not called during server-side rendering, because only the first rendering will take place on the server side.
    • Updated Function This hook is called after the virtual DOM is rerendered and patched due to data changes.
    • **activatedFunction ** Called when the keep-alive component is active. This hook is not called during server-side rendering.
    • Deactivated Function keep-alive is invoked when the component is disabled. This hook is not called during server-side rendering.
    • BeforeDestroyFunction Called before the instance is destroyed. At this step, the instance is still fully available. This hook is not called during server-side rendering.
    • DestroyedFunction Called after the Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all child instances are destroyed. This hook is not called during server-side rendering.
    • errorCaptured(2.5.0+ added)(err: Error, vm: Component, info: string) => ? booleanCalled when catching an error from a descendant component. This hook takes three arguments: the error object, the component instance where the error occurred, and a string containing information about the source of the error. This hook can return false to prevent the error from propagating upward.

What are the forms of vUE component communication (i.e., value transmission) and how are they implemented

There are three types of vUE communication: parent-child communication, child-parent communication, and brother-to-brother communication

Vue Encapsulates slot functions of components

  • The VUE package component involves three things
    • Events (v – on, $emit)
    • Pass the props
    • slot: Slot is used to distribute content. Content can be nested within component labels<slot></slot>To define placeholder content
      • There are named slots and anonymous slots
  • When writing reusable components, it pays to always consider whether the components are reusable. It’s ok for disposable components to be tightly coupled to other components, but reusable components must define a clear exposed interface


  • The vue.js component API comes from three parts:Prop, event, and slot
    • Prop allows external environments to transfer data to components. Vuex can also be used in VUe-CLI projects to transfer data
    • Events allow a component to trigger actions in the external environment (i.e., actions, which means methods)
    • Slot allows an external environment to insert content into a component’s view structure



How to achieve vUE transition animation

Vue transitions are implemented through the Transition component provided in VUE

<transition name= "name" >< router-view></router-view> </transition>Copy the code

Describe your understanding of unidirectional data flow

  • Data is always passed from the parent to the child. The child maintains its own data internally, but it has no right to modify the data passed to it by the parent. When the developer tries to do so, vUE will report an error. This is done for better maintenance between components.
  • In development, there may be multiple child components that depend on the parent component’s data, if the child component can modify the parent component’s data
    • A change in a child component causes all the children that depend on the data to change, so vue does not recommend that children modify the parent’s data

Vue bidirectional data binding principle

A: The core is mainly implemented using ES5 ** object.defineProperty **, and then use the getter and setter to achieve two-way data binding, and that’s about it. It’s actually a little more complicated to implement than this, but I’ve seen it


  • Using H5’s History API
    • Mainly throughHistory. PushState and history. ReplaceStateTo do that. The difference is,pushStateWill add a new history record, andreplaceStateThe current history is replacedWhen publishing projects, you need to configure Apache
  • Hash implementation using url
    • We see this a lot in urls#There are two cases where # is called an anchor. Instead of calling an anchor, we call it a hash. We’re talking about hashes, and we listen for hash changes to trigger eventsHashchange eventsTo do partial page updates
  • Summary: The hash scheme is compatible, and H5’s History is mainly for advanced browsers

Here are the specific API differences:

this.$router.push(location, onComplete? , onAbort?) // This method adds a new record to the history stack, so when the user clicks the browser back button, it returns to the previous URL <router-link :to="..." > is equivalent to calling router.push(...) this.$router.replace(location, onComplete? , onAbort?) This method does not add a new record to history. Instead, it does what its method name does -- it replaces the current history record. So, when the user clicks the browser back button, it does not return to the previous URL. How many steps forward or backward in the history record, similar to window.history.go(n)Copy the code
  • This may lead to a new interview question:The difference between replace and push
    • It can be said that in the past, a secondary route was configured in a project with a TAB switch section (details, comments, instructions), because when returning to the previous page, there was no way to switch back and forth between the tabs. So I used it**this.$router.replace**Methods, don’t count**history**In the record, so you don’t have to switch over and over again**bug**

Understanding of vUE route hooks (or VUE route guards)

  • A VUE route hook intercepts information about the current route and the route to be jumped during the route jump. There are three types of route hooks
    • Global routing hook
beforeEach(to,from,next){}Copy the code
  • Hooks exclusive to the route
beforeEnter(to,from,next) {

  }
Copy the code
  • Hooks within a component
beforeRouteEnter(to,from,next) { 
   / /...
}
beforeRouteUpdate(to,from,next) {
  / /...
}

beforeRouteLeave(to,from,next) {
   / /...
}

Copy the code
  • Application scenarios: Dynamically setting the page title and determining the user login permission: Code examples
// Global Route navigation guard
vueRouter.beforeEach(function (to, from, next) {
    const nextRoute = [ 'detail'];
    const auth = sessionStorage.getItem("username");    
    let FROMPATH = from.path;
    // Go to the above three pages
    if (nextRoute.indexOf(to.name) >= 0) {
    	// The path in the array is equivalent to the page with permission, and the page in the arraylist should be logged in
        if(! auth) {let params = Object.assign({frompath:FROMPATH},from.query);
			next({path: '/newlogin'.query:params}); }}// If you have logged in, go to the login page and jump to the home page
    if (to.name === 'newlogin') {
        if (auth) {
// vueRouter.push({name: 'index'});
 			next({path: '/'});  
        }
    }
    next();
});

Copy the code

What problem does the lazy vUE route load solve?

The lazy vUE route loading mainly solves the problem that the file is too large after packaging. The JS in the corresponding component is loaded only after the event is triggered


  1. The route was loaded lazily. Procedure

  1. The Gzip compression function is enabled

  1. Use the Externals property of WebPack to separate out libraries that don’t need to be packaged, reducing the size of the packaged files

  1. Server Rendering with Vue (SSR)



  • Both the cross-domain front-end and back-end can be implemented. If only for VUE, VUE itself can be implemented by proxy
    • Configure proxy in index.js in config to implement this:

  • “Use scaffolding reverse proxy (proxy) in the development process, and configure CORS at the back end when going online (if CORS need to automatically pass cookie, the front end also needs to be configured)

Differences between Methods,computed, and watch in Vue

  • Methods are encapsulated functions that are triggered regardless of whether there are changes
  • Computed: a unique vUE attribute that computes a dependency in data to get a new value and apply it to the view. The essential difference between computed and methods is that computed is cacheable, which means that the dependency in Computed is unchanged. The values in computed are not recalculated, and the functions in Methods are not cached.
  • Watch listens for new and old changes in data and computed properties.
  • What does Vue bind to events with, and what properties with
    • Use v-ON to bind the event (@) and V-bind to bind the property (:)

How does VUE dynamically add attributes to achieve data response?

  • Vue is mainly used byThis.$set(object, 'property', value)Add, as I recall, if you change the value of a property of a reference type, you can render it automatically.

How are HTTP requests managed in VUE

If HTTP requests in VUE are scattered in various components of VUE, it is not easy to maintain and manage in the later period. Therefore, business requirements are usually stored in a unified directory for management in a project

  • For example, in the API folder under SRC, all the wrapped HTTP requests used by the component are exported and imported into other components. Consider the HTTP request encapsulated below



Your understanding of the Axios interceptor

The AXIos interceptor allows us to automatically intercept and handle back-end HTTP requests and responses in a project, reducing the amount of code required for requests and responses, improving development efficiency and facilitating maintenance later in the project

Such as:





Or you can manipulate public data



The difference between Vue and Jquey

  • Jquery is primarily a dom manipulation “magic”, powerful selector, encapsulates a lot of easy to use dom manipulation methods and how to obtainAjax methods such as $.ajax () are very useful
  • Vue: Used mainly for data-driven and componentization, rarely for dom manipulation, although vUE may passRef to select a DOMOr components


  • CSS does not have the concept of local styles, and vue scaffolding is implemented by adding scoped to the style TAB

Vue third-party UI style library how to achieve style penetration (UI library and less/sass penetration problem) >>> /deep/




Vue directory structure (you may ask about the vUE project directory structure during the interview)

Is the Vue scaffolding built by your company or using Vue’s script scaffolding? What do you know about WebPack?

Our company uses the official vUE scaffolding (VUe-CLI). The vue-CLI version is 3.0 and 2.9.x

  • Webpack is a front-end modular packaging build tool. Vue scaffolding itself is built with WebPack. The entry file required by WebPack itself is specified by entry, and the exit file is specified by output
  • For example, lessless,less-loaderSass needsass-loaderCSS needstyle-loader,css-loaderTo implement.
  • Of course, there are some built-in plug-ins to compress and merge files

Say what you think of VUEX

How vuEX implements data persistence (that is, data remains after refreshing)

  • Since the state in vuex is stored in memory and is lost once refreshed, such as login state, the solution is:
  • The first: use H5’s local storage(localStorage,sessionStorage)
  • Second: use third-party encapsulated plug-ins, such as:vuex-persistedstate

  • Third: use vue-cookie plug-in to do storage

  • Fourth: the data can be passed to the background, stored in the database


Application scenario:

  • One: sometimes need to dynamically add events for some DOM elements on the page according to the data, which requires to set when the DOM elements are rendered, but the created and Mounted functions are generally not rendered, so there will be a problem that can not get, add the event, this time will use nextTick processing
  • Second, if you are using a third-party plug-in and want to reapply the plug-in when some dom generated by Vue changes dynamically, you need to perform the reapplication method in the callback function of $nextTick.
    • For example, when better- Scroll is applied



  • Get focus after data changes


Let’s start with a scenario where you have a div that is hidden by default with V-if. You click a button, change the value of V-if, make it appear, and get the text content of the div. If the value of v-if is false, you cannot retrieve the content of the div directly, because the div has not been created yet. Then you should change the value of v-if to true after clicking the button. Then you can retrieve the content of the div again.

<div id="app">
    <div id="div" v-if="showDiv">This is a text</div>
    <button @click="getText">Get div content</button>
</div>
<script>
var app = new Vue({
    el : "#app".data: {showDiv : false
    },
    methods: {getText:function(){
            this.showDiv = true;
            var text = document.getElementById('div').innnerHTML;
             console.log(text); }}})</script>

Copy the code

This code is not hard to understand, but when run, it throws an error in the console: Cannot read property ‘innnerHTML of null, which means that the div element Cannot be retrieved


  • Instead of updating the DOM directly when Vue sees a change in data, it starts a queue and buffers all data changes that occur in the same event loop. When buffering, duplicate data is removed to avoid unnecessary computation and DOM manipulation. Then, in the next event loop, Tick, Vue refreshes the queue and performs the actual (deduplicated) work. So if you use a for loop to dynamically change the data 100 times, it only applies the last change. Without this mechanism, the DOM would have to be redrawn 100 times, which is a lot of overhead.
  • Vue preferentially uses native based on the current browser environmentPromise. Then and MutationObserverIf neither is supported, then setTimeout is used instead.
  • Given how Vue asynchronously updates the DOM, the error in the above example is not difficult to understand. In fact, when this.showdiv = true is executed, the div will still not be created until the next vue event loop. The $nextTick is used to know when the DOM update is complete, so the above example code needs to be changed to:
<div id="app">
    <div id="div" v-if="showDiv">This is a text</div>
    <button @click="getText">Get div content</button>
</div>
<script>
var app = new Vue({
    el : "#app".data: {showDiv : false
    },
    methods: {getText:function(){
            this.showDiv = true;
            this.$nextTick(function(){
                  var text = document.getElementById('div').innnerHTML;
                 console.log(text); }); }}})</script>
Copy the code

Click on the event, and the console prints out the contents of the div, “This is a piece of text.” In theory, we should not have to actively operate the DOM, because the core idea of Vue is data-driven DOM, but in many businesses, we can’t avoid using some third-party libraries, such as Popper. js, Swiper, etc., which are based on native javascript have a complete life cycle of creation, update, and destruction. When used with Vue, take advantage of the $nextTick.

The priority of v-for and V-IF

When they are on the same node, V-for has a higher priority than V-if, which means that V-IF will be repeated separately in each V-for loop. This priority mechanism is useful when you want to render nodes for only a few items, such as:

<li v-for="todo in todos" v-if=! "" todo.isComplete">
  {{ todo }}
</li>
Copy the code

The above code only passes unfinished Todos. If your goal is to conditionally skip the execution of the loop, place v-if on the outer element (or

Function of the keep-alive component in vUE

Keep-alive: Used primarily to preserve component state or avoid rerendering.

Such as: Have a details list page and a page, so users will often perform open details = > to return to the list = > open details such word lists and details are very high frequency of a page, so it can be used to list component caching, so every time the user returned list, can render quickly from the cache, rather than to render.

  1. Properties:
    1. Include: a string or regular expression. Only matching components are cached.
    2. Exclude: indicates a string or regular expression. Any matching components are not cached
  2. Usage:
    1. When wrapping dynamic components, inactive component instances are cached rather than destroyed. and<transition>Similar,<keep-alive>Is an abstract component: it does not render a DOM element itself, nor does it appear in the parent component chain.
    2. When the component in<keep-alive>In versions 2.2.0 and later,The Activated and deactivated life cycles are triggered in all nested components in the tree.


  • How do you learn new skills?
    • Read the documents on the official website, find relevant open source projects on Github and practice, attend technical discussion on the technical community blog Park, CSDN, 51CTO, Digigong, Brief book, on Zhihu, learn systematically through professional books (such as: High Level 3, javascript authoritative guide, i.e. rhino book), and join relevant technical groups for reference and discussion
  • What are your future career plans?
    • In two years, the first technology, small success, other opportunities will slowly come
  • Leaving reason
    • The company’s capital chain is broken. I can’t get paid for two months. The boss told me to look for a job
    • The industry as a whole is not doing well. On the company side, the proportion of variable pay (performance pay) has increased
    • The company needs a long-term overseas business trip, and some of my personal friends are all in Beijing, so I don’t want to go out.
    • The company project is complete. The rest is just maintenance work. The company has recruited two new college students. I took them for two months
    • To be determined…

Common interview

  • To introduce myself

My name is XXX. I have been engaged in front-end development for several years. I master the following technologies: HTML, CSS, H5, C3, javascript bootstrap framework, including: Vuex Eleemntui axios Echart… React technology station React ANTd axios Redux version management tool WebPack in the past few years: Adaptation issues REM Flex responsive IE9 V -for rendering data in Option, characters are not displayed issues select style interface security issues via virtual DOm: Interface send and request unified encryption, through the key verification there are many common problems, I summarized a document, I believe these are no longer a problem, I hope to join our company to make our company’s project more humane

  • Problems encountered in the project: Project introduction Self introduction