1, xiao Bai’s common concept confusion and common skills

1) Literals and builders

Literals are divided into object literals, array literals, and string literals

The new Object() constructor new Array() constructs an Array

First, the pros and cons

  1. Object literals are more convenient to declare than functions
  2. An empty object is essentially just a data structure that satisfies the following conditions:
    • The __proto__ attribute points to Object.prototype
    • Its membership list points to an empty shell
    var obj3 = new Object();
    var num = 0;
    for(var i inobj3){ num++; } console.log(num); / / 0Copy the code

Object members can be accessed following two rules:

  1. The attributes and methods in the member table are preferentially accessed when read.
  2. If there is no specified attribute in the member table, the entire stereotype chain of the object is queried until the attribute or the top of the stereotype chain is found. So it is more efficient to access properties in an instance than in a prototype. We should use literal syntax to create objects
    var Student = function() {
            this.name = 'default';
            this.say = function() {
                console.log('say hello! ');
            }
    }
    var s1 =new Student();
    console.log(window.name)
Copy the code

New, this points to the global object inside the student, if not defined.

So here’s a quick summary of the relationship between constructors, stereotypes, implicit stereotypes, and instances:

Each constructor has a prototype property that points to the constructor’s prototype object.

The instance Object has an implicit prototype attribute (PROTO) that points to the constructor’s prototype Object (obj.proto==Object.prototype); The instance object also has a constructor property in its prototype object, which points to the constructor.

2) This is in call, apply and bind

Fn. call(asThis, p1, p2) is the normal way to call a function. If you are unsure of the number of arguments, use apply fn.apply(asThis, params).

Bind, call, and apply call functions directly, whereas bind returns a new function (without calling the original function) that calls the original function with parameters specified by you.

3) Skills of using MAP

Const fruitColor = newMap().set()'red'['apple'.'strawberry'])
    .set('yellow'['banana'.'pineapple'])
    .set('purple'['grape'.'plum']);
function test(color) {
  return fruitColor.get(color) || [];
}
Copy the code

4) Typeof array or null determines the type value of object

5) How SVG is written

<svg class="icon"><use :xlink:href="`#i-${icon}`"></use></svg> 
Copy the code

6) Debouce and Thorlle

  • Debouce definition: the action will not be executed until n milliseconds after the action is called, and the execution time will be recalculated if the action is called again after n seconds
  • Thorlle definition: Throttling ignores subsequent callback requests.
functionCreateDebounce (callback, time) {var timer time = time | | 300 / / the default valuereturn function () {
        if (timer) {
              clearTimeout(timer);
        }

        timer = setTimeout(()=>{
              callback()
        }, time)
  }
}

Copy the code
// fn is the event callback we need to wrap, and interval is the threshold of the time intervalfunctionThrottle (fn, interval) {// last indicates the time when the callback was last triggeredletLast = 0 // Return throttle as a functionreturn function () {
          letContext = this // Preserves the arguments passed in the callletArgs = arguments // Record the time when the callback is triggeredletNow = +new Date() //if(now - last >= interval) { last = now; fn.apply(context, args); }}}Copy the code

7) If judge some pit

Conditional statements such as if statements use the ToBoolean abstraction method to enforce the evaluation of their expressions and always follow the simple rule:

  • Objects evaluates to true
  • Undefined evaluates to false
  • Null evaluates to false
  • Booleans are evaluated as Boolean values
  • Numbers evaluates to false if it is +0, -0, or NaN, and true otherwise
  • Strings evaluates to false if it is an empty string “, true otherwise
// Explainif([0] && []) {//true// An array (even an empty array) is an object, and objects are evaluated totrue
}
Copy the code

8) Deep and shallow copies

  1. Deep copy of the
  • JSON. Stringify with JSON. The parse

    2. Shallow copy

  • assign
var o1 = { a: 1 }; var o2 = { b: 2 }; var o3 = { c: 3 }; var obj = Object.assign(o1, o2, o3); console.log(obj); // { a: 1, b: 2, c: 3 } console.log(o1); // {a: 1, b: 2, c: 3}, the target has changedCopy the code
  • The expansion operator…

9) Array

(function s(){
    const value="0";
    const arrNo = ["", null, "0", 0, "undefined", undefined];
    if(arrNo.some(d => d === value)) return console.log('Not the desired value')
})()
Copy the code

10) Array

var arry1 = [1, 2, 3]; arry1.forEach((item, index, arr)=>{ console.log(arr[index]); //1, 2, 3})Copy the code

11) Array. The from

let hours = [];
for(leti =0; i<24; i++){ hours.push(i +'when'} // We can write it in the following formlet hours = Array.from({length:24}, (value, index) => index + 'when')
Copy the code

12) For in, for of

for(letI of nums){of = VALUEinThe values inside are key, for... The of statement iterates over the iterable defining the data to be iterated over. for... The IN statement iterates over the enumerable properties of an object in the original insertion order. }Copy the code

13) Extended operator abbreviations

const odd = [1, 3, 4]; const nums = [2, 5, 6, ...odd]; The console. The log (nums) / /,5,6,1,3,4 [2]Copy the code

14) Optimism and pessimism lock (do not know which god named)

Pessimistic lock definition: When submitting a form, to prevent multiple submissions, we prefix the request with a flag bit

        var block = false    
        function refesh() {if(block){
                return 
            }
            block = true

            return fetch('api')
                .then(res => {
                    block = false
                })
                .catch(err =>{
                    block = false})}Copy the code

Optimistic lock definition: the user clicks on another component before the resource is downloaded, and we download another resource. The previous request is made as usual, but it is discarded anyway.

        var id = 0
        function loading(resources){
            var load_id = ++id
            PromiseAll(resources)
                .then(()=>{
                    ifLoad_id === id {// render}else{// discard}}). Catch ()=>{if(load_id ===id){
                        //提示错误
                    } else{// discard}})}Copy the code

15) Proxy

The object takes two parameters, the first parameter is the object to be operated on, and the second parameter is to set the corresponding interception property. The property here also supports GET, set, etc., that is to hijack the corresponding element read and write, can perform some operations in it, and finally return a Proxy object.

const proxy = new Proxy({}, {
  get(target, key) {
    console.log('proxy get key', key)
  },
  set(target, key, value) {
    console.log('value', value)
  }
})
proxy.info     // 'proxy get key info'
proxy.info = 1 // 'value 1'Const me = {name:"Xiao Ming", like: "Little red", food: "Mushroom", musicPlaying: true
            };

            // const meWithProxy = new Proxy(me, {
            //     get(target, prop) {
            //         if (prop === "like"{/ /return "Learning"; / / / /}return target[prop];
            //     }
            // });
            const meWithProxy = new Proxy(me, {
                set(target, prop, value) {
                    if (prop === "musicPlaying"&& value ! = =true) {
                        throw Error("Any attempt to stop the music is hooliganism!"); } target[prop] = value; }}); //console.log("sale_check mounted", meWithProxy.like);
            console.log.log("sale_check mounted", meWithProxy.food);
            console.log("sale_check mounted", meWithProxy.musicPlaying = false);
Copy the code

Little white vue’s way into the pit

1. V-if in VUE uses key to manage reusable elements

We add the corresponding key to the input box that is not to be reused, and the label element is still reused efficiently.

        <template v-if="loginType === 'username'">
            <label>Username</label>
            <input placeholder="Enter your username" key="username-input">
        </template>
        <template v-else>
            <label>Email</label>
            <input placeholder="Enter your email address" key="emial-input">
        </template>
Copy the code

2. Dynamically insert the corresponding script

3. The computed and watch

A calculated property is, as its name implies, another property computed from another variable, and a calculated property has a cache. Computed properties are cached based on their dependencies. A calculated property is reevaluated only if its associated dependencies change.

The listener watch listens for a specific value and executes a specific function when that value changes. In the paging component, for example, we can listen for the current page number and perform the corresponding function to get the data when the page number changes

  1. In terms of attribute name, computed is a calculation of attributes, that is, the final value computed by relying on other attributes. Watch is to listen for a value change and then execute the corresponding function.
  2. In terms of implementation, computed values are cached after GET is executed, and the corresponding getter will be called again the next time a computed value is obtained after the attribute value it depends on changes. Watch executes a callback every time the value it listens for changes. From this point of view, the callback is executed after the value of the dependency changes. A lot of functions are already available with a lot of properties, but there are more suitable ones.

If a value depends on multiple attributes (many-to-one), using computed is certainly more convenient. If a change in value causes a series of operations, or if a change in value causes a series of changes (one-to-many), watch is more convenient.

  1. The watch callback passes in the old and new values of the listening properties, which can be used to perform specific operations. Computations usually mean simple calculations. Here is the interchange between the two
    <input >
    
        watch: {
            word() {
                this.$emit("update:keyword", this.word); }} Define word computed: {word: {get() {
                    return this.keyword;
                },
                set(val) {
                    this.$emit("update:keyword", val); }}}Copy the code

4. Some notes on refs usage

Ref is used to register reference information for an element or child component. The reference information will be registered with the parent component’s $refs object.

Important note about ref registration times: Because ref’s are themselves created as render results, you can’t access them during initial render – they don’t exist yet! $refs is also not reactive, so you should not attempt to use it to do data binding in templates. You should avoid accessing $refs in templates or calculated properties. Also, considering the uniqueness of their refs, for example, if two forms are the same, only the latter one will be referenced.

5. Parent and child component communication

< / father/Child - one: parentMessage ="parentMessage" @childEvent='childtMethod'></Child-one>

methods:{
    childMethod(){
        alert('Component messages'}} // < button@click ="childMethod"</button> props:{parentMessage:{type: String,
        default: 'Subcomponent'
    }
}
methods:{
    childMethod(){
        this.$emit('childEvent'.'Component information')}}Copy the code

6. Data transfer of non-parent and child components can be adopted

Prop is a one-way data flow, so the data received by PROP cannot be bound bidirectionally

Child component throughOn (eventName) to listen for events,

  • Define a local variable and initialize it with the value of prop:
props:['initialCounter'],
data:function() {return {counter: this.initialCounter}
}
Copy the code
  • Define a calculation property that handles the value of prop and returns it.
props:['size'],
computed:{
    normalizedSize:function() {return this.size.trim().toLowerCase()  
    }
}
Copy the code

7.vue.extend

1. Using the vue constructor, create a subclass that takes an object containing component options. Conclusion: Vue.extend actually creates an extension instance constructor, initializes the corresponding constructor, and mounts it to the tag

8.vue.mixins

Conclusion:

  • Mixins are executed in the order mixins>mixinTwo>created(lifecycle hooks for Vue instances);
  • Create (){console.log(‘ this is the vue instance’s getSum ‘)}; -3. Extends is similar to mixins except that it takes a simple option object or constructor as an argument, so extends only one component at a time

Conclusion: 1. Extends extends> Mixins >mixinTwo> Created 2. Attribute override rules defined are consistent with mixins

9.vue.install

Install is the plug-in that develops vue. The first argument to this method is the Vue constructor, and the second argument is an optional option object (optional). The vue.use method can call install, which automatically prevents the same plug-in from being registered multiple times.

let install = function(Vue){
	components.map(component=>{
		Vue.component(Vue.component.name, Vue.component)
	})
}
Copy the code

Just to summarize the differences

  • Vue. extend and vue.use can be used to build their own UI library
  • Vue.extend and Vue.component are used to create constructors and components;
  • Mixins and extends are to extend components;
  • Install is a development plug-in;

Total order: vue. extend>Vue.component>extends>mixins

10. The function of component name

  1. When the item uses keep-alive, the component name can be used for cache filtering
  2. When DOM is a recursive component, for example, the detail.vue component has a list.vue subcomponent, and recursive iteration calls its own name
  3. When you use vue-DevTools, the names of the groups displayed in the vue-DevTools debugging tool are determined by the name of the vUE component

11. Watcher has two configurations

(1) Watcher deep: true (2) This callback will be called immediately after listening starts with immediate: true

12.beforeDestroy

Vue’s beforeDestroy () lifecycle hook is a good place to solve such problems in vue Router-based applications. BeforeDestroy: function () {this. ChoicesSelect. Destroy ()} can be used with deactivated, you can remove the keep alive – hook

13.keep-alive

When you wrap a component with keep-alive, its state is preserved and therefore remains in memory.

other

1. The diff algorithm

The main function of key in VUE is to update the virtual DOM efficiently. The main logic is as follows

2. Cache differences between GET and POST

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.

3. Execution sequence of setTimeout, process.nextTick, and PROMISE

Event Loop queue tasks include macro tasks and micro tasks

Common macro-tasks include setTimeout, setInterval, setImmediate, Script, I/O, UI rendering, etc.

Common micro-tasks include Process. nextTick, Promise, MutationObserver, etc. Macro-task tasks are executed one by one, while micro-Tasks are executed in teams.

Their execution priority is process.nextTick> Promise >setTimeout

4. Min-width and max-width of the CSS

Min-width inherits the parent element,min-height does not inherit the parent element, and if there is no parent element (i.e. the outermost body element), the default is 100%


  • These are some of the problems, techniques, or confusing concepts you may encounter at work. I hope they can help some people. Due to the limited ability, may be misunderstood, welcome to point out.
  • Don’t spray if you don’t like it. Thank you
  • Shenzhen pit can contact me qq:1039460820, or leave your contact information in the comment area.