preface

From front-end learning to find a suitable job, large and small interview is essential, so I have a preliminary arrangement of the primary front end questions, but also convenient for their own reference, but also hope to help partners!

HTML

Semantic HTML

HTML semantematization is about structuring the content of a page, and it has the following advantages

1, easy for users to read, style loss can make the page show a clear structure. 2, conducive to SEO, search engines according to the label to determine the context and the weight of each keyword. 3, convenient for other devices to parse, such as blind readers according to the semantic rendering of web pages 4, conducive to development and maintenance, semantic more readable, better maintenance of the code, and CSS3 more harmonious relationshipCopy the code

Such as:

<header> represents the header, <nav> represents the hyperlink area. <main> defines the main content of a document. <article> can represent articles, blogs, etc. <aside> usually represents a sidebar or embedded contentCopy the code

HTML 5 new label

<header>, <footer>, <aside>, <nav>, <video>, <audio>, <canvas>, etc...Copy the code

CSS

The box model

Box model is divided into standard box model and weird box model (IE model)

Box-sizing: content-box // Box-sizing: border-box //Copy the code

As shown below, the overall width and height are still 120px

div{
    box-sizing: content-box;
    margin: 10px;
    width: 100px;
    height: 100px;
    padding: 10px;
}
Copy the code

Weird box model: Element width equals width in style

As shown below, the overall width and height are still 100px

div{
    box-sizing: border-box;
    margin: 10px;
    width: 100px;
    height: 100px;
    padding: 10px;
}
Copy the code

Note: If you find that the content area of your design page is oversized, check what border-sizing is and make it easy to manage when referencing reset.css

Difference between REM and EM

Rem is based on the font size of the root, while EM is based on the font size of the parent

Rem: relative to the font size of the root HTML element, if the HTML is font size: 12px, then the div in it is set to font size: 2rem, so that the middle div is 24px

Em: relative to the parent element, if a p element is 12px and has a span tag inside it, set it to 2em, then the span font size is 12*2=24px

CSS selectors

CSS common selectors

Wildcard: * ID selector:#IDClass selector:.class element selector: p, a descendant selector: P span, div a pseudo-class selector: A :hover attribute selector: input[type="text"] etc.Copy the code

CSS selector weights

! Portant -> inline style -> #id ->.class -> elements and pseudo-elements -> * -> Inheritance -> default

CSS features

-Howard: Transition to a transform, zoom, move, or tilt animation gradient shadow border-radiusCopy the code

Inline elements and block-level elements

Inline elements (display: inline)

The width and height are determined by the content. Elements that are on a line with other elements are called inline elements, such as , < I >, , etc

Block level elements (display: block)

The default width is determined by the parent container, the default height is determined by the content, and the elements that have a single line and can be set to width and height are called block-level elements, such as

,

,

    , etc

In normal times, we often use CSS display: inline-block to give them more states

The difference between absolute and relative positioning

Position: Absolute: is the closest positioned ancestor element relative to the element

A relative position is relative to an element’s initial position in the document

Flex layout

Juejin. Cn/post / 684490…

BFC

What is landing?

The BFC formatting context, which is a separate rendering area, isolates the elements inside the BFC from the elements outside, so that the positioning of the elements inside and outside does not affect each other

How to generate BFC?

display: inline-block

position: absolute/fixed

Landing the role of

One of the biggest uses of the BFC is to have a separate container on the page so that the layout of elements inside and outside the container does not affect each other

Solve the upper margin overlap; BFC is enabled for both overlapping boxes; Solve floating caused by height collapse; Container box open BFC solution text surround picture; Left image div, right text container P, open BFC for container PCopy the code

Horizontal and vertical center

Flex layout

Display: flex // set flex mode flex-direction: column // determine whether the element is horizontal or vertical flex-wrap: wrap // determine whether the element is context-content: Space between / / under the same row alignment, blank space to separate each element align - items: center / / how to align the align - under the same row of elements content: space between / / alignmentCopy the code

Horizontal center

Inline elements: display: inline-block; Margin: 0 auto; Flex: display: flex; justify-content: centerCopy the code

Vertical center

Flex: display: flex; align-item: centerCopy the code

Less, Sass,styus

variable

Sass declares that variables must begin with “$” followed by the name and value of the variable, and that the name and value are separated by a colon:.

Less declares variables with “@” at the beginning, the rest of the same as Sass.

Variables declared in Stylus are not qualified; the ending semicolon is optional, but there must be an “equal sign” between the variable name and its value.

scope

Sass: The worst of the three, there is no concept of global variables

Less: The last updated variable is valid and applies to all references!

Stylus: The processing method of Sass is the same as that of Stylus. The output value of a variable is calculated according to the last previous definition, and each reference to the latest definition is valid.

nested

The “selector nesting” of the three CSS precompilers is identical in use, even to the tags that refer to the parent selector

inheritance

Sass inherits styles from one selector to another, much like Stylus. Start with “@extend”, followed by the inherited selector. Stylus inherits from Sass in the same way. Less uses pseudo class to describe inheritance relationship.

Import @ Import

Variable interpolation can only be done in Sass when a URL () expression is introduced

$device: mobile;
@import url(styles.#{$device}.css);
Copy the code

Less allows interpolation in strings

@device: mobile;
@import "styles.@{device}.css";
Copy the code

Interpolation doesn’t work here in Stylus, but you can take advantage of its string concatenation capabilities

device = "mobile"
@import "styles." + device + ".css"
Copy the code

conclusion

Sass and Less have strict syntax, while Stylus is relatively free. Because Less looks more like CSS, it might be easier to learn.

Sass and Compass, Stylus and Nib are good gay friends.

Sass and Stylus both have language-like processing in a logical way: conditions, loops, and so on, whereas Less needs to simulate these functions with keywords like When, which makes Less sense than Sass and Stylus

Less is inferior to the Sass and Stylus in richness and character, and if Bootstrap hadn’t introduced Less, it probably wouldn’t be as widely used as it is today (personal opinion)

Link and @import are distinguished and selected

<style type="text/css"> @import url(CSS file path address); </style> <link href="CSSurl path" rel="stylesheet" type="text/css" /
Copy the code

Link has many functions, such as RSS, Rel, etc., while @import can only be used to load CSS.

When a link is parsed, the page loads the referenced CSS synchronously, while the CSS referenced by @import waits until the page is loaded.

@import requires Internet Explorer 5 or higher.

Link can be dynamically imported using JS, @import cannot

Ellipsis of text for multi-line elements

overflow : hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical
Copy the code

JavaScript

JS several basic specifications

1. Do not declare multiple variables on the same line. = = to comparetrue/falseSwitch statements must have a default branch 6. Functions should not sometimes return a value, sometimes not 7. For loops must use curly braces 8.forVariables in the -in loop should be explicitly scoped using the var keyword to avoid scope contaminationCopy the code

JS reference method

Inline introduced

<body>
  <input type="button" onclick="Alert (' inline introduced ')" value="Button"/>
  <button onclick="alert(123)"</button> </body>Copy the code

introducing

<script>
  window.onload = function() {
    alert("Js internally introduced!");
  }
</script>
Copy the code

External introduction

<body>
  <div></div>

  <script type="text/javascript" src="./js/index.js"></script>
</body>
Copy the code

Pay attention to

1, it is not recommended to insert <script> in the line or HTML, because the browser parse order, if parsing into JS code such as an infinite loop, will jam the page 2, it is recommended to execute the code after the onload event, that is, after the HTML and CSS rendering is completedCopy the code

JS basic data type

Undefined, Null, Boolean, Number, String, add :Symbol

An array of operating

One of the most used things in JavaScript is undoubtedly array manipulation, so here’s a look at some of its uses

Map: Iterates through arrays of numbers, returning a new array of callback returnsforEach: can'tbreakWe can stop filter by throwing a new Error in a try/catch. Some: returns an itemtrue, the whole istrueEvery: One item is returnedfalse, the whole isfalseJoin: generate string push/pop by specifying the concatenator, change the array, return push/pop item unshift /shift: head push and pop up, change the original array, returning to action items [wrong] sort (fn)/reverse: sorting and inversion, change the original array concat: connection arrays, does not affect the original array, shallow copy slice (start, end) : Return splice(start, number, value...) IndexOf/lastIndexOf(value, fromIndex): fromIndex: fromIndex: fromIndex: fromIndex: fromIndex: fromIndex Find the array item and return the corresponding subscript reduce/reduceRight(fn(Prev, cur), defaultPrev): perform in pairs, prev is the last reduction functionreturnValue, cur is the current value (starting with the second term)Copy the code

What built-in objects do JS have

Object is the parent Object of all JavaScript objects: Object, Array, Boolean, Number, and String Other objects: Function, Arguments, Math, Date, RegExp, ErrorCopy the code

Error in the length of get request parameters

Myth: It is often said that get request parameters are limited in size and POST request parameters are unlimited in size

In fact, the HTTP protocol never specifies a limit on the length of a GET/POST request. The restriction on get request parameters is the source and browser or Web server, which limits the length of the URL. To clarify this concept, we must reiterate the following points:

1. HTTP does not specify length limits for GET and POST

2. The maximum length of GET is displayed because browsers and Web servers limit the length of urIs

3. Different browsers and WEB servers have different maximum length limits

4. If Internet Explorer is supported, the maximum length is 2083 bytes; if only Chrome is supported, the maximum length is 8182 bytes

Fill in the cache differences between GET and POST requests

  • Get requests are similar to lookups in that the user retrieves data without having to connect to the database every time, so caching can be used.

  • Unlike Post, which generally does modification and deletion, it must interact with the database, so it cannot use caching. Therefore, GET requests are suitable for request caching.

closure

What is a closure?

If function A contains function B and function B uses variables of function A, function B is called A closure.

Or: closures are functions that can read variables inside other functions

function A() {
  var a = 1;
  function B() {
    console.log(a);
  }
  return B();
}
Copy the code

Characteristics of closures

  • Function nested inside function
  • Inner functions can refer to outer parameters and variables
  • Parameters and variables are not collected by garbage collection

Understanding closures

Closures are used primarily to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables, but the disadvantage is that closures will live in memory, which will increase the memory usage, and improper use will easily cause memory leaks. In JS, functions are closures, and only functions have the concept of scope

Closures are useful for reading variables inside functions and for keeping them in memory at all times

Closures are also useful for encapsulating the private properties and methods of an object

Benefits of closures

Can achieve encapsulation and caching, etc

Disadvantages of closures

It is the memory consumption, improper use will cause memory overflow problem

Considerations for using closures

Because closures cause variables in functions to be stored in memory, which can be very memory consuming, you should not abuse closures, which can cause performance problems for web pages and memory leaks in IE

The solution is to remove all unused local variables before exiting the function

The classic problem with closures

for(var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}
Copy the code

This code outputs

First of all, there are three of them.forA loop is a synchronized code that executes three timesforI becomes 3; Then, the asynchronous code is executedsetTimeout, I can only output three 3'sCopy the code

What is the way to print 0, 1, 2

The first way

Use the let

for(let i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}
Copy the code

Here, each let is combined with a code block to form a block-level scope, and when setTimeout() prints, it looks for I in the nearest block-level scope, so 0, 1, 2 are printed in sequence

If this is not clear, we can execute the following code

for(let i = 0; i < 3; i++) {
  console.log("Timer outside:" + i);
  setTimeout(function() {
    console.log(i);
  }, 1000);
}
Copy the code

The browser outputs:

External timer: 0 External timer: 1 External timer: 2 0 1 2Copy the code

The code still executes the for loop first, but when the for loop ends and setTimeout is reached, it flags it so that in console.log(I), I can find the most recent variable definition in the block

The second way

Use immediate functions to solve closure problems

for(let i = 0; i < 3; i++) {
  (function(i){
    setTimeout(function() {
      console.log(i);
    }, 1000);
  })(i)
}
Copy the code

JS scope and scope chain

scope

In JavaScript, scopes are divided into global scopes and function scopes

Global scope

Code can be accessed anywhere in the program, and the window object’s built-in properties have global scope

Function scope

Only fixed snippets of code can be accessed

Example:

The greatest use of a scope is to isolate variables. Variables of the same name in different scopes do not conflict.

Variable value: to the scope of the function that created the variable

The scope chain

Normally, a variable takes a value in the scope of the function that created it.

But if no value is found in the current scope, the chain is called the scope chain

Prototype and prototype chain

The concept of prototype and prototype chain

Every object initializes a property inside of it, called prototype. When we access an object’s property, if the property doesn’t exist inside the object, the object will look for the property in Prototype, which in turn will have its own prototype. And so it went on and on

The relationship between prototypes and prototype chains

instance.constructor.prototype = instance.__proto__
Copy the code

Characteristics of prototypes and prototype chains

JavaScript objects are passed by reference, and each new object entity we create does not have a copy of its own prototype. When we modify the stereotype, the objects associated with it inherit the change

When we need a property, the Javascript engine looks first to see if the property is present in the current object, and if it isn’t

It looks up whether its Prototype Object has this property, and so on, until it reaches the Object built-in Object

Componentization and modularization

componentization

Why componentize development

Sometimes the amount of page code is too large, too much logic or the same functional component is used in many pages, so the maintenance is quite complex. At this time, it is necessary to componentalize development to carry out function splitting and component encapsulation, which has achieved component versatility, enhanced code readability and greatly reduced maintenance cost

Advantages of componentized development

Greatly reduce the coupling of various functions of the system, and improve the integration of internal functions. It is of great benefit to front-end engineering and reduce the maintenance of the code. The reduction of coupling improves the extensibility of the system, reduces the complexity of development, improves the development efficiency and reduces the development cost

Principles of componentized development

  • single-minded

  • configurability

  • standard

  • reusability

  • maintainability

modular

Why modularity

Early versions of javascript had no block-level scope, no classes, no packages, and no modules, which led to problems like reuse, dependencies, conflicts, and disorganized code. Modularity became imperative as the front end expanded

Benefits of modularity

  • Avoid variable contamination and naming conflicts

  • Improve code reuse

  • Improved maintainability

  • Facilitate dependency management

Several approaches to modularization

  • Function encapsulation
var myModule = {
    var1: 1,
    
    var2: 2,
    
    fn1: function(){
    
    },
    
    fn2: function() {}}Copy the code
Conclusion: This avoids variable contamination, as long as the module name is unique, and the members of the same module also have a relational flaw: external members can sleepily modify internal members, which can cause unexpected security problemsCopy the code
  • Execute function expressions now (IIFE)
var myModule = (function(){
    var var1 = 1;
    var var2 = 2;
    
    function fn1(){
    
    } 
    
    function fn2(){
    
    }

return{ fn1: fn1, fn2: fn2 }; }) ();Copy the code
Conclusion: There is no way to modify variables outside the module that we haven't exposed. Disadvantages: relatively weak functionality, encapsulation adds work, still leads to namespace contamination, closures are costlyCopy the code

Preloading and lazy loading of images

  • Preloading: Images are loaded ahead of time and rendered directly from the local cache when the user needs to view them
  • Lazy loading: The main purpose of lazy loading is to serve as a front-end optimization for the server, reducing the number of requests or delayed requests

The essence of two technologies: the behavior of both is opposite, one is early loading, one is slow or even not loading. Preloading increases the front-end pressure of the server, and lazy loading relieves the pressure to a certain extent.

The difference between mouseover and MouseEnter

Mouseover: Events are triggered when the mouse moves over an element or its child, so there is a repetitive, bubbling process. The corresponding remove event is mouseout

Mouseenter: When the mouse removes the element itself (any child element that does not contain the element), it triggers an event that does not bubble. The corresponding remove event is mouseleave

Solve asynchronous callback hell

Promise, generator, async/await

Understanding This object

This always refers to the direct (not indirect) caller of the function

If you have the new keyword, this refers to the object that new came out of

In an event, this points to the object that triggered the event. In particular, this in An attachEvent in IE always points to the global object Window

Vue

Vue life cycle

What is the Vue lifecycle?

The lifecycle of a Vue instance is the process from creation to destruction. We call this the life cycle of a Vue, which starts with creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, and unmounting

What is the role of the Vue lifecycle?

It has multiple event hooks throughout its lifecycle, making it easier to form good logic when controlling the process of an entire Vue instance

How many phases are there in the Vue life cycle?

It can be divided into 8 stages altogether: before/after creation, before/after load, before/after update, and before/after destruction

Which hooks are triggered the first time the page loads?

BeforeCreate, Created, beforeMount, and Mounted are triggered the first time a page is loaded

In what cycle is DOM rendering completed?

DOM rendering is done in Mounted

What scenarios are appropriate for each lifecycle?

Some ways to use lifecycle hooks:

Beforecreate: You can add a loading event here, which is triggered when the instance is loaded

Created: This is where the initialization event is written. For example, this is where the loading event ends and asynchronous requests are called

Mounted: A DOM node is obtained after an element is mounted

Updated: If data is treated uniformly, write the corresponding function here

BeforeDestroy: You can make a confirmation box that acknowledges the stop event

NextTick: Dom manipulation immediately after data update

V-show is different from V-if

V-show is CSS switching, v-if is complete destruction and re-creation

Use V-show for frequent switching and v-if for less frequent changes at runtime

V-if = ‘false’ V-if is conditional rendering and will not render when false

What are the common instructions in development

V-model: Generally used to express input, it is easy to achieve form controls and data binding in both directions

V-html: Updates the innerHTML of an element

V-show vs. V-if: conditional rendering, note the difference

When v-if is used, if the value isfalse, then the page will not have this HTML tag generating v-show is regardless of the value oftrueorfalseHTML elements are always present, but display in CSS is shown or hiddenCopy the code

V-on: click: can be shortened to @click,@ binds an event. If the event is triggered, you can specify the event handler v-for: to render an element or template block multiple times based on the source data V-bind: to apply the DOM in response to changes in the expression’s value

Grammar: v - bind: title ="msg"Abbreviations: : title ="msg"
Copy the code

Bind the array usage of class

V-bind :class=”{‘orange’: isRipe, ‘green’: isNotRipe}”

Array method V-bind :class=”[class1, class2]”

V-bind :style=”{color: color, fontSize: fontSize+’px’}”

Value-passing communication between components

Parent component passes value to child component

With props, the parent component can use props to pass data to the child component

The parent component vue template father.vue

<template>
    <child :msg="message"></child>
</template>

<script>
import child from './child.vue';
export default {
    components: {
        child
    },
    data () {
        return {
            message: 'father message';
        }
    }
}
</script>
Copy the code

Child component vue template child.vue:

<template>
    <div>{{msg}}</div>
</template>

<script>
export default {
    props: {
        msg: {
            type: String,
            required: true
        }
    }
}
</script>
Copy the code

The child component communicates with the parent component

The parent component passes event methods to the child component, which fires events via $emit and calls back to the parent component

Parent component vue template father. Vue:

<template>
    <child @msgFunc="func"></child>
</template>

<script>
import child from './child.vue';
export default {
    components: {
        child
    },
    methods: {
        func (msg) {
            console.log(msg);
        }
    }
}
</script>
Copy the code

Child component vue template child.vue:

<template>
    <button @click="handleClick"</button> </template> <script>export default {
    props: {
        msg: {
            type: String,
            required: true}},methods () {
        handleClick() {/ /... this.$emit('msgFunc');
        }
    }
}
</script>
Copy the code

Communication between non-parent and sibling components

You can use a VUE instance Bus as a medium to introduce Bus into the sibling components that want to communicate with each other, and then implement communication and parameter passing by calling Bus event trigger and listener respectively

Bus.js can look like this:

import Vue from 'vue'
export default new Vue()
Copy the code

Introduce bus.js to all components that need to communicate:

<template>
	<button @click="toBus"</button> </template> <script> import Bus from'.. /common/js/bus.js'
export default{
	methods: {
	    toBus () {
	        Bus.$emit('on'.'From sibling component')
	    }
	  }
}
</script>
Copy the code

Another component also imports bus.js to listen for on events in hook functions

import Bus from '.. /common/js/bus.js'
export default {
    data() {
      return {
        message: ' '}},mounted() {
       Bus.$on('on', (msg) => {
         this.message = msg
       })
     }
   }
Copy the code

Route jump mode

1, < the router - link to ='home'> Router-link tags are rendered as <a> tags. 2, the other is programming navigation, which is to jump through js, such as router.push('/home')
Copy the code

MVVM

M-model, Model stands for data Model, you can also define the business logic for data modification and manipulation in Model V-View, View stands for UI component, which is responsible for converting data Model into UI and presenting it vM-ViewModel, A ViewModel listens for changes in Model data, controls the behavior of the View, and handles user interactionsCopy the code

What is the difference between computed and Watch?

computed:

1. Computed is a calculated attribute, that is, a calculated value, which is more commonly used in scenarios where values are calculated. 2. The next time the value of computed data is obtained, the corresponding getter is invoked for calculation. 3. Computed data is applicable to computing scenarios that consume performanceCopy the code

watch:

1. More "observation" function, similar to some data listening callback, used to observe props$emitOr the value of this component, when the data changes to perform the callback for subsequent operations 2. No caching, the page is re-rendered when the value does not change will also be executedCopy the code

Summary:

1. When we do numerical calculations and rely on other data, design this data for computed 2. If you need to do something when the data changes, use Watch to watch the data changeCopy the code

key

The key is the unique ID marked for the Vnode in the Vue, and with this key we can make diff operations more accurate and faster

Accuracy: If no key is added, vUE will choose to reuse the node (vUE’s in-place update strategy), resulting in the state of the previous node being preserved, resulting in a series of bugs

Fast: The uniqueness of the key can be fully exploited by Map data structures

Why is data in a component a function?

Why does data in a component have to be a function and then return an object, while data in a New Vue instance can be an object?

// data
data() {
  return {
	message: "Subcomponent",
	childName:this.name
  }
}

// new Vue
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {App}
})
Copy the code

Because components are used for reuse, objects in JS are reference relationships, so there is no scope isolation, and instances of New Vue are not reused, so there is no reference object problem

How to bind Class and Style dynamically?

Classes can be dynamically bound using object syntax and array syntax:

Object syntax

<div v-bind:class="{ active: isActive, 'text-danger': hasError }"></div>

data: {
  isActive: true,
  hasError: false
}
Copy the code

Array syntax

<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>

data: {
  activeClass: 'active',
  errorClass: 'text-danger'
}
Copy the code

Style can also be dynamically bound with object syntax and array syntax:

Object syntax

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

data: {
  activeColor: 'red',
  fontSize: 30
}
Copy the code

Array syntax

<div v-bind:style="[styleColor, styleSize]"></div>

data: {
  styleColor: {
     color: 'red'
   },
  styleSize:{
     fontSize:'23px'}}Copy the code

Single data flow for VUE

All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand

Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. If a child component wants to modify it, it can only send a custom event through $emit. If the parent component receives the custom event, the parent component can modify it

There are two common situations when trying to change a prop:

This prop is used to pass an initial value; This child component next wants to use it as a local prop data

In this case, it is best to define a local data property and use this prop as its initial value:

props: ['initialCounter'],
data: function () {
  return {
    counter: this.initialCounter
  }
}
Copy the code

This prop is passed in as a raw value and needs to be converted

In this case, it is best to use the value of the prop to define a calculated property

props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}
Copy the code

keep-alive

Keep-alive is a built-in component of Vue that can preserve the state of contained components and avoid re-rendering. It has the following features:

  • It is used together with routing and dynamic components to cache components.
  • Provide include and exclude attributes. Both of them support strings or regular expressions. Include indicates that only components with matching names will be cached, and exclude indicates that components with matching names will not be cached.
  • The hook function activated is activated when a component is activated, and the hook function deactivated is activated when a component is removed.

V – the principle of the model

Vue project mainly uses V-Model instructions to create two-way data binding on form input, textarea, SELECT and other elements. We know that v-Model is essentially nothing more than syntax sugar. Internally, V-Model uses different attributes and throws different events for different input elements:

  • Text and Textarea elements use value attributes and input events;
  • Checkbox and radio use the Checked attribute and the change event;
  • The SELECT field takes value as prop and change as an event;

Take the input form element for example:

<input v-model='something'>
Copy the code

The equivalent of

<input v-bind:value="something" v-on:input="something = $event.target.value">
Copy the code

If in a custom component, the V-Model defaults to use a prop named Value and an event named input, as follows:

Parent component: <ModelChild V-model ="message"></ModelChild> Subcomponent: <div>{{value}}</div> props:{value: String}, methods: {test1(){
     this.$emit('input'.'little red')}},Copy the code

nextTick()

A deferred callback is performed after the next DOM update loop ends. Immediately after the data is modified, the callback function is used to get the updated DOM

// Modify data vm. MSG ='Hello'// DOM has not been updated with vue.nexttick (function() {// DOM update})Copy the code

Vue slot

Individuals can also feel this article wrote: www.cnblogs.com/chinabin199…

A single slot

When the child component template only has a slot with no attributes, the entire content fragment passed in by the parent component is inserted into the DOM where the slot is, replacing the slot label itselfCopy the code

Named slot

Solt elements can be further configured to distribute content with a special property name. Multiple slots can have different names. This associates slot locations in the parent component template with slot elements in the child component, facilitating slot content transferCopy the code

Scope slot

In the parent, the <template> element with the special property slot-Scope must exist to indicate that it is a template for the scoped slot. The value of slot-scope will be used as the name of a temporary variable that receives the prop object passed in from the child componentCopy the code

Vue-router has several navigation hooks

BeforeEach (to,from,next) intercepts before jumping

Second: hooks within components

Third: separate route exclusive component

vuex

What is vuex?

Vuex is a repository of objects. Where state is where the data source is stored, corresponding to the data state in the general VUE object, the data stored in the vUE is responsive. The VUE component reads the data from the Store. If the data in the store changes, Components that rely on this data also get updates that map global state and getters to computed properties of the current component via mapStateCopy the code

Vuex has 5 properties: State, getter, mutation, Action and Module.

State Vuex uses a single state tree, where each application will contain only one store instance, but a single state tree is not incompatible with modularity. The state of the stored data cannot be modified directly

Mutations The method defined by Mutations dynamically modifies the state or data in Vuex’s store

Getters is a vUe-like computational attribute that filters data

Action Actions can be understood as a method that transforms the data in mutations into a method that can process the data asynchronously. Simply speaking, it is an asynchronous manipulation of data. The View layer distributes actions through store.dispath

In conclusion, VUEX is generally used for medium and large web single-page applications to manage the application state. For some small applications with relatively simple relationship between components, it is not necessary to use VUEX, because the communication between parent and child components can be completed by using component prop properties or events. Vuex is more used to address cross-component communication and centrally store data as a data center

What optimizations have you made to the Vue project?

Optimization at the code level

V-if and V-Show Discriminating Use Scenarios Computed and Watch Discriminating Use Scenarios V-for traversal You must add keys to items. And avoid simultaneously using v-if long list performance optimization event destruction image resource lazy load route lazy load third-party plug-in on demand optimization infinite list performance server render SSR or pre-renderCopy the code

Optimization at the Webpack level

Webpack compresses images to reduce ES6 to ES5 redundancy code extraction Common code templates precompile extract components CSS optimization SourceMap Build results output analysis Vue project compile optimizationCopy the code

Optimization of basic Web technologies

Enable gzip compression. Use Chrome Performance to find Performance bottlenecksCopy the code

ES6

Var, let, const

Var declarations can be repeated, while let declarations cannot be repeated

Var is not limited to the block level, while LET is limited to the block level

Var maps to Window (hanging an attribute), while let does not map to Window

Var can access a variable above a declaration, while let has a temporary dead band. Accessing a variable above a declaration will result in an error

Const must be assigned after the declaration or an error will be reported

Const defines an immutable quantity, and an error is reported if it changes

Const, like let, does not map to window, supports block-level scope, and raises an error when accessing a variable above a declaration

Deconstruction assignment

An array of deconstruction

let [a, b, c] = [1, 2, 3]   //a=1, b=2, c=3
let[d, [e], f] = [1, [2], 3let[g,...h] =[1, 2, 3]let[I,j] = [1, 2, 3] // Discontinuous deconstruction I =1, j=3let[k,l] = [1, 2, 3Copy the code

Object to deconstruct

let {a, b} = {a: 'aaaa', b: 'bbbb'}      //a='aaaa' b='bbbb'
let obj = {d: 'aaaa', e: {f: 'bbbb'}}
let{d, e:{f}} = obj'aaaa' f='bbbb'
let g;
(g = {g: 'aaaa'}) // Destruct g= with declarative variables'aaaa'
let [h, i, j, k] = 'nice'// String destruct h='n' i='i' j='c' k='e'
Copy the code

Definition of function parameters

In es5 syntax, if a function is called with multiple parameters, the parameters must correspond to each other. Otherwise, an assignment error will occur.

function personInfo(name, age, address, gender) {
  console.log(name, age, address, gender)
}
personInfo('william', 18.'changsha'.'man')
Copy the code

In the above example, four parameters need to be passed to the user information, and they need to be matched one by one, so it is easy to pass the wrong order of parameters, resulting in a bug. Let’s see how ES6 deconstruction assignment solves this problem:

function personInfo({name, age, address, gender}) {
  console.log(name, age, address, gender)
}
personInfo({gender: 'man', address: 'changsha', name: 'william', age: 18})
Copy the code

So we just know that we need to pass the declaration parameters, we don’t need to know the order of the parameters

Swap the values of variables

In ES5 we need to swap the values of two variables with the help of temporary variables. Here is an example:

var a=1, b=2, c
c = a
a = b
b = c
console.log(a, b)
Copy the code

Let’s see how ES6 works:

let a=1, b=2;
[b, a] = [a, b]
console.log(a, b)
Copy the code

Is it more convenient to write than es5

Function default arguments

In everyday development, there is often a case where a function argument needs a default value, and an error will be reported if it is used without a default value.

function saveInfo(name, age, address, gender) {
  name = name || 'william'
  age = age || 18
  address = address || 'changsha'
  gender = gender || 'man'
  console.log(name, age, address, gender)
}
saveInfo()
Copy the code

Error: if main is set to a default value, then avoid using it.

function saveInfo({name= 'william', age= 18, address= 'changsha', gender= 'man'} = {}) {
  console.log(name, age, address, gender)
}
saveInfo()
Copy the code

Default parameters are defined at the time of the function definition, so that you don’t have to assign default values to parameters later

ForEach, for in, for of

ForEach is more used to iterate over numbers

For in is usually used to iterate over objects or JSON

Keys () and object.keys ().

For in loops for key, for of loops for value

What should I pay attention to when using arrow functions?

This cannot be used as a constructor, which means you cannot use the new command; otherwise, an error will be thrown. Therefore, arrow functions cannot be used as Generator functions

The difference between Set and Map

Application Scenario Set is used for data reorganization, and Map is used for data storage

Set: 1, the member can not duplicate 2, only the key value without the key name, similar to array 3, can be traversed, add, delete,has methods

Map: 1 is essentially a collection of key pairs, similar to set 2, that can be traversed and converted to various data formats

Write a promise by hand

Promise is a constructor, and here is a simple example

var promise = new Promise((resolve,reject) => {
    ifResolve (value)}else {
        reject(error)
    }
})
promise.then(function (value) {
    // success
},function (value) {
    // failure
})

Copy the code

Ajax

How do I create an Ajax

(1) Create an XMLHttpRequest object, that is, create an asynchronous call object (2) create a new HTTP request and specify the method, URL, and validation information for the HTTP request (3) set up a function that responds to changes in the status of the HTTP request (4) send the HTTP request (5) Get the data returned by the asynchronous call (6) Use JavaScript and DOM to achieve local refresh

The difference between synchronous and asynchronous

Synchronization: When the browser requests the server, the user sees the page refresh and sends the request again. After the request is complete, the page is refreshed and the user sees the new content and performs the next operation

Asynchronous: The browser requests from the server. The user performs normal operations and the browser requests from the back end. When the request is finished, the page is not refreshed, the new content will also appear, and the user will see the new content

Advantages and disadvantages of Ajax

The advantages of ajax

1. Update data without refreshing (maintain communication with the server without refreshing the whole page) 2. Communicate with the server asynchronously (communicate with the server in an asynchronous way without interrupting user operations) 3. 4, interface and application separation (Ajax interface and application separation, namely data and presentation separation)

The disadvantage of ajax

Ajax does not support the browser back button. 2. Security Issues Aajax exposes the details of the server interaction. 3

Get and POST

2. Get is less secure than POST. 3. Get is cached, but POST is not. 6. Get accepts only ASCII characters as parameter data types, and there is no restriction on POST. 7. Get requests will retain historical records, but parameters in POST will not be retained. Post will submit the request again

When to use post?

Post is generally used to modify resources on the server and has no restrictions on the information sent. Such as

Unable to use cached files (update files or databases on the server) 2. Sending large amounts of data to the server (POST has no data limit) 3. Sending user input containing unknown characters POST is more stable and reliable than GET

How to solve cross-domain problems

The concept of cross-domain is that the protocol, domain name, and port must be the same. Otherwise, it is cross-domain

Solving cross-domain problems:

CORS (cross-domain resource sharing), cross-domain configuration on the backend. 3. Server proxy, which allows access to third-party resources through server files

What are Ajax and JSON, and their advantages and disadvantages

Ajax:

Ajax is asynchronous JavaScript and XML for asynchronous data interaction in Web pages

Ajax advantages:

Asynchronous request fast response, good user experience; No page refresh, partial data update; On-demand data, reducing redundant requests and server burden;

Ajax faults:

Asynchronous callback problem, this pointing problem, route jump back problem; Search engine support is weak and not very good for some phones

JSON:

Is a lightweight data interchange format that looks like an object but is essentially a string

JSON advantages:

Lightweight, easy to read and write, easy to parse JS, support composite data types

JSON faults:

It’s not as popular and widely used as XML, it’s not as universal

Github

Git common commands

Clone from remote repository to local: The repository address on the Git site

Git add command to add files.

Git commit -m or git commit -a

Check your workspace: git status -s

Git fetch/git merge or Git pull

Git reflog command to view the commit record

webpack

Webpack packaging principles

Webpack is simply a mechanism for packaging modules and simply turning dependent modules into static files that represent those packages. Webpack is the entry file that identifies you. Identify your module dependencies to package your code. Whether your code is using CommonJS or AMD or ES6 import. Webpack will analyze it. To get the code’s dependencies. What WebPack does is analyze the code. Transform code, compile code, output code. Webpack is a node module, so webpack.config.js is written in CommonJS (modularity in Node is the CommonJS specification).

Module hot update

Module hot update is a feature of Webpack that enables code changes to be updated without refreshing, the advanced version of the auto-refresh browser

In devServer, hot replacement of modules can be controlled through the hot property

Through the configuration file

const webpack = require('webpack');
const path = require('path');
let env = process.env.NODE_ENV == "development" ? "development" : "production";
const config = {
  mode: env,
 devServer: {
     hot:true}} plugins: [new webpack HotModuleReplacementPlugin (), / / thermal load plugins], module. Exports = config;Copy the code

Through the command line

 "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."start": "NODE_ENV=development webpack-dev-server --config webpack.develop.config.js --hot",},Copy the code

How to speed up WebPack building

1. Use externals to extract common libraries

2. Use DllPlugin and DllReferencePlugin to precompile resource modules using DllPlugin to precompile NPM packages that we reference but never modify, and then load the precompiled modules using DllReferencePlugin

3, use Happypack to achieve multi-threaded accelerated compilation

The first thing to note is that it doesn’t support file-loader and url-loader very well, so these two loaders don’t need to be happypack, other loaders can be changed similarly

Use tree-shaking and Scope as a buffer to remove redundant code. Replace sass-loader with fast-sass-loader

The cacheDirectory parameter or transform-Runtime plugin can be added to the babel-loader to create common files that duplicate during runtime

// webpack.config.js
use: [{
    loader: 'babel-loader',
    options: {
        cacheDirectory: true
}]
// .bablerc
{
    "presets": [
        "env"."react"]."plugins": ["transform-runtime"]}Copy the code

No need to package compiled plug-in libraries with the global “script” tag introduced the way

JQuery plugin, React, react-dom, etc., it’s a lot of code, it’s a lot of time to package it up. Then use the expose-Loader or externals or ProvidePlugin in the Webpack configuration to provide the corresponding variables for use inside the module

// @1
use: [{
    loader: 'expose-loader',
    options: '$'
    }, {
    loader: 'expose-loader',
    options: 'jQuery'
    }]
// @2
externals: {
        jquery: 'jQuery'
    },
// @3
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery'.'window.jQuery': 'jquery'
        }),
Copy the code

8. Optimize the search path at build time

When WebPack is packaged, there are all kinds of paths to query and search, and we can add some configuration to make it search faster for example, module paths that are easy to change to absolute paths, Use the resolve alias alias field and exclude to exclude files that do not need to be traversed

The advantages of webpack

Focus on dealing with modular projects, can do out of the box, one step in place

Plugin can be extended, complete and easy to use and flexible

Usage scenarios are not limited to Web development

The community is large and active, often introducing new features that keep up with The Times, and you can find existing open source extensions for most scenarios

Good development experience

The disadvantage of webpack

The downside of WebPack is that it can only be used for projects with modular development

Wechat applets

Main contents and functions of files

- component —————————————————— Component folder - navBar - Bottom component - navbar. js - JS code for bottom component - navbar. json - Configuration file for bottom component - WXSS -- CSS code of the bottom component -- pages ————————————————————— Page folder -- index -- Home page -- index.js WXML -- HTML code of the home page -- index.wxss -- CSS code of the home page -- public -- -- -- -- -- -- -- -- -- -- - picture folder - utils -- -- -- -- -- -- -- -- -- -- -- tools folder - API. Js - control API file - md5. Js - tools - md5 encrypted file - Timestamp. Js - tools - timestamp files - app. Json -- -- -- -- -- -- -- -- --, set the global data, and so on the basis of - app. WXSS -- -- -- -- -- -- -- -- -- --, common style, You can import more -project.config. json ———————— project configuration files by using importCopy the code

Wechat applets life cycle

OnLoad () : Triggered when the page loads. OnShow () : triggered when the page is displayed/cut to the foreground. OnReady () : Triggered when the first rendering of the page is complete. OnHide () : triggered when the page is hidden or in the background. OnUnload () : Triggered when a page is unloaded.Copy the code

How to encapsulate data requests

1. Encapsulate interfaces

Project/utils/API. Js

Const fetch = ({url, data}) => {console.log(' 【step 1】API:${url}`);
  console.log("【step 2】 Data input:); console.log(data); / / return Promisereturnnew Promise((resolve, reject) => { wx.request({ url: getApp().globalData.api + url, data: data, success: Res => {// Processing on successif (res.data.code == 0) {
          console.log(【step 3】 Request success:);
          console.log(res.data);
          return resolve(res.data);
        } else {
          wx.showModal({
            title: 'Request failed',
            content: res.data.message,
            showCancel: false}); }}, fail: err => {// Processing console.log(err);returnreject(err); }})} /** * code for openId * @data {* jsCode - wx.login() return code *} */export const wxLogin = data => {
  return fetch({
    url: "tbcUser/getWechatOpenId",
    data: data
  })
}
Copy the code

2. Call the interface

Project/pages/login/login. Js

import {
  wxLogin,
} from '.. /.. /utils/api.js'
Copy the code

3. Use interfaces

Project/pages/login/login. Js

wxLogin({
  jsCode: this.data.code
}).then(
  res => {
    console.log("[step 4] Return a successful processing:);
    console.log(res.data);
  },
  err => {
    console.log("[step 4] Return failure processing:); console.log(err); })Copy the code

Page data passing

Carry parameters through the URL. In onLoad(), use options to get parameters on the URL:

<navigator url=".. /index/index? userId={{userId}}"></navigator> <! OnLoad = onLoad ();function(options) {
  console.log(options.userId);
}
Copy the code

Pass parameters through Storage:

wx.setStorageSync('userId'.'jsliang');
wx.getStorageSync('userId');
Copy the code

WXML passes data to JS

login.wxml

<text bindtap="clickText" data-labelId="{{userId}}"> Click pass data to JS</text>Copy the code

login.js

clickText(e) {
  console.log(e.currentTarget.labelid)
}
Copy the code

Component calls pass parameters

Component receives data: component-tag-name

Component({properties: {// Here we define the innerText property. The value of the property specifies the innerText: {when used by the Component.type: String,
      value: 'default value',}}})Copy the code

Define JSON using the component’s page

{
  "usingComponents": {
    "component-tag-name": ".. /component/component"}}Copy the code

Use the component’s page HTML code

<view> <! This is a reference to a custom component --> <component-tag-name inner-text="Some text"></component-tag-name>
</view>
Copy the code

Pass parameters through interface calls

Load performance optimization method

This.$preload() preloads the second page the user might click on

2, componentized page, appear more than two parts are packaged into components

Extract common CSS styles

4. Optimized image: TinyPNG

Differences between wechat applets and native APP, Vue and H5

Wechat applet advantage

2. Faster opening speed 3. Lower development cost than native APP

Disadvantages of wechat small program

1. More restrictions. The page size should not exceed 1M, and the page of more than 5 levels should not be opened. 2. Small program internal components have become permanent, the style can not be modified 3, narrow promotion. Can not run out of wechat, can not run into the circle of friends

Micro channel small program VS native APP micro channel small program has the advantages of low development cost, low customer cost, no download

Wechat small program VS H5 1, rely on different environments. One runs in multiple mobile browsers. An incomplete browser that only works in wechat 2. Development costs vary. One may have problems in various browsers. One can only work in wechat

Wechat mini program looks like a castrated version of Vue

Micro channel small program principle

It’s essentially a single page application, where all the page rendering and event processing happens on one page

The architecture is data-driven mode, UI and data are separated, and all page updates need to be realized through changes to the data

Wechat applets are divided into two parts: WebView and appService. Among them, WebView is mainly used to display UI, and appServer is used to process business logic, data and interface call. They are carried out in two processes, through the system layer JSBridge to achieve communication, UI rendering, event processing

Similarities and differences between WXML and standard HTML

WXML is based on XML design, and tags can only be used in wechat mini programs, not HTML tags

Network protocol

The network layer

At present, network stratification can be divided into two types: OSI model and TCP/IP model

OSI model Application layer Presentation layer Session layer Transport layer Network layer Data Link layer Physical

TCP/IP model Application Host-to-host Transport Layer Internet Network Interface layer

HTTP/HTTPS

2. HTTP is a hypertext transfer protocol that transmits information in plaintext, while HTTPS is a secure SSL encryption transfer protocol. 3. 4. HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.

The HTTP status code

Discriminant Status code 1 x x start – Information 2 x X start – The request succeeds 3 x X start – The request is redirected 4 x X start – Request error 5 x X start – Server error

Common status code 200 – Request successful, Ajax received message 400 – Server does not understand request 403 – server rejected request 404 – Request page error 500 – Server internal error, unable to complete the request

Performance optimization

HTML optimization

1. Avoid writing CSS code in HTML as it is difficult to maintain. 2. Use Viewport to speed up page rendering. Use semantic tags to reduce CSS code, increase readability and SEO. 4, reduce the use of tags, DOM parsing is a large traversal process, reduce unnecessary tags, can reduce the number of traversal. 5. Avoid null SRC, href, etc., because browsers will initiate HTTP requests even if they are null. 6. Reduce the number of DNS queriesCopy the code

CSS optimization

1. Optimize the selector path: use.c {} instead of.a.b. c {}. 2. Selector merge: common attribute content is lifted to compress space and resource overhead. 3, Precise style: Use padding-left: 10px instead of padding: 0, 0, 10px. Sprite images: Combine small ICONS into one image so that all images only need to be requested once. Avoid wildcard:.a. b * {}, according to the parse order from right to left in the parsing process encountered wildcard * {} 6, will traverse the entire DOM, performance significant loss. 7, use lessfloat:floatFlex layouts can be used when rendering is more computationally intensive. 8, for 0 value to unit: increase compatibility. 9, compress the file size, reduce the burden of resource download.Copy the code

JavaScript to optimize

1, as far as possible to put the <script> tag after the body, to avoid JS execution stuck DOM rendering, to ensure the page as soon as possible to display 2, as far as possible to merge JS code: extract public methods, object-oriented design...... 3, CSS can do things, as far as possible not JS to do, after all, JS parsing execution is rougher, and CSS is more efficient. 4. Manipulate the DOM as much as possible, and pre-order CSs styles to reduce reflow or repaint. 5. Create the DOM as little as possible and use display: None in HTML and CSS to hide and display as needed. 6, compress the file size, reduce the burden of resource download.Copy the code

Other common interview questions

Often ask

2. What are the technical difficulties in your project? What’s the problem? How did you solve it? Which project do you think did the best? 4. How do you learn front-end development? 6. How did you learn the front end

The personnel face

Do you have any questions you would like to ask after the interview What are your greatest strengths and weaknesses? 4. Why did you choose this industry? Do you think you are suitable for this position? 6. What career plan do you have? 7. What are your salary expectations? 8. How do you view front-end development? 9. What is the plan for the next three to five years?

other

What is your understanding of refactoring?

Network refactoring: The act of simplifying structure and adding readability while maintaining consistency at the front end of a site without changing external behavior. The idea is to optimize the site without changing the UI, and maintain a consistent UI while extending it

For traditional websites refactoring is usually:

  • Table layout changed to DIV+CSS
  • Make the front end of the site compatible with modern browsers (against substandard CSS, such as IE6)
  • Optimization for mobile platforms
  • Optimize for SEO

What kind of front-end code is good?

High reuse low coupling, so that the file is small, easy to maintain, and easy to expand

How do you understand the position of front End engineer? What are its prospects?

The front end is the programmer closest to the user, closer than the back end, database, product manager, operations, and security

  • Interface interaction
  • Improve user experience
  • With Node.js, the front end can do some things on the server side

The front end is the programmer closest to the user, and the power of the front end is to evolve a product from a 90 to a 100 or better,

Communicate with team members, UI design, product manager;

Good page structure, page reconstruction and user experience;

Where do you see the value of front-end engineering?

1, provide technical support to simplify the users (interaction) 2, 3, provide support for multiple browser compatibility in order to improve the user browsing speed (performance) to support 4, based on its or other rendering engine for cross-platform or other support of the application of 5, and provide support for displaying data (data interface)

How do you manage your projects?

  • The initial team must determine the global style (globe.CSS), encoding pattern (UTF-8), etc.

  • The writing habits must be consistent (for example, each style is written in a single line using inheritance);

  • Annotation style writer, all modules are timely annotation (annotation key style call place);

  • Annotate pages (e.g. start and end of page modules);

  • CSS and HTML should be stored in parallel folders and named in the same way (for example, style.css).

  • JS folders store English translations named according to the JS function.

  • Images are used in integrated images.png pNG8 format files – try to integrate them together to facilitate future management

Mobile terminal (Android IOS) how to do a good user experience?

Clear visual vertical lines, grouping of information, extreme subtraction, use of selection instead of input, layout of labels and text, reliance on clear text to confirm passwords, reasonable keyboard use