vue learning notes

(3) array de duplication

 let arr = [1, 2, 34, 34, 5, 6, 6, 7];

      function arryQC(arr) {
        // The first
        // return Array.from(new Set(arr))

        // Second
        return [...new Set(arr)];
      }
      console.log(arryQC(arr));

      console.log(
        "==============This is the second method indexOF==============================="
      );

      let arr1 = [1, 2, 34, 34, 5, 6, 6, 7];

      function arryQCs(arr) {
        let brr = [];
        arr.forEach((element) => {
          if (brr.indexOf(element) === -1) {
            brr.push(element);
          }
        });
        console.log(brr);
      }
      arryQCs(arr1);

      console.log(
        "==============This is the third method filter==============================="
      );

      let arr2 = [1, 2, 34, 34, 5, 6, 6, 7];

      function arryQC3(arr) {
        const result = arr.filter((item, index) => {
          return arr.indexOf(item) === index;
        });
        console.log(result);
      }
      arryQC3(arr2);

      console.log(
        "==============This is the fourth method reduce==============================="
      );

      let arr3 = [1, 2, 34, 34, 5, 6, 6, 7];

      function arryQC3(arr) {
        const result = arr.reduce((pre, item) => {
          return pre.includes(item) ? pre : [...pre, item];
        }, []);
        console.log(result);
      }
      arryQC3(arr3);

(5) deep copy

 // Implementation: deep copy
      // Note: write the judgment of Array type first (because the parent class of Array is Object, no matter the Array Object is written on it, it will be included)
      let newObj = {};
      function deepClone(newO, old) {
        for (let key in old) {
          let value = old[key];
          if (value instanceof Array) {
            newO[key] = []; // What is copied is an array. Create a new array
            deepClone(newO[key], value);
          } else if (value instanceof Object) {
            newO[key] = {}; // New object
            deepClone(newO[key], value);
          } else {
            newO[key] = value; // Basic type, pure value copy
          }
        }
      }
      deepClone(newObj, oldObj);
      console.log(newObj,'=============',oldObj);

      // Summary: deep copy
      // Recurse the reference type of each layer, create a new one when encountering an object / array, and copy the basic value

(6) differences between cookies.sessionstorage and localStorage

cookies: a piece of data used by a website to mark the identity of a user. Usually, it is an encrypted string, and by default, it will only be carried in the HTTP request of the same source

sessionStorage: it is a local storage mode of the browser. It is stored in the form of key value pairs. The stored data will be automatically deleted after the browser is closed

localStorage: it is a way of local storage of the browser. It is stored in the form of key value pairs. It stores persistent data, which is not deleted actively and will always exist

sessionStorage and localStorage are larger than cookies

7 throttling and anti vibration

Anti shake
function debounce(fn, theTime) {
           let timer = null
            return function () {
                clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.call(this);
                }, theTime);
            }
        }
throttle
 function throttle(fn,timer) {
            return function () { // Real event handler (this: event source)
                if (fn.t) return;
                fn.t = setTimeout(() => {
                    fn.call(this) // Make sure the this keyword in the above function is the event source (fn() calls, and the above this becomes window, which is wrong)
                    fn.t = null // Set to null, and re create a timer when the event is triggered again
                }, timer)
            }
        }

Difference between shallow copy and deep copy

       * Shallow copy: only refers to the copied memory address. If the original address changes, the shallow copy object will change accordingly
       * The old and new objects share memory. Modifying one of them will also affect the other
       * Method 1: direct assignment
       * Method 2: object.assign()
       * 
       * Deep copy: create a new address in memory for storing copied objects
       * Old and new objects will not share memory, and modifying one of them will not affect the other
       * 
       * Method 1: JSON object
       * 
       *  let obj = {name:'Zhang San',age:20}
          const obj1 = JSON.parse(JSON.stringify(obj))
          obj1.age = 22
          console.log(obj.age,'==============',obj1.age); // 20 '==============' 22
       * 
          Method 2: extension operator
          let obj = { name: "Zhang San", age: 20 };
          let obj1 = {...obj,age:25}
          console.log(obj.age, "==============", obj1.age); // 20 '==============' 25


     

reduce sum

 const arr = [
        { id: 1, name: "watermelon", state: true, price: 10, count: 1 },
        { id: 2, name: "Pumpkin", state: false, price: 20, count: 2 },
        { id: 3, name: "Balsam pear", state: true, price: 30, count: 3 },
      ];

        let amt = 0
        // The first
        // arr.filter(item => item.state).forEach(item => {
        
        //   amt += item.price * item.count
        // }) 
        
        // The second type is reduce
        // arr.filter(item => item.state). Reduce ((cumulative result, current cycle item) = >, initial value)

       const result = arr.filter(item => item.state).reduce((amt,item) => {
          return amt += item.price * item.count
        },0)

       console.log(result);

(1) Vue route parameter transmission

1 params Pass on reference
this.$router.push({
        name:"admin",
    //Here, params is an object, ID is the attribute name, and item.id is the value (it can be directly taken from the current component or Vue instance)
        params:{id:item.id}
})

//Routing configuration corresponding to this component
{
  //Component path
    path: '/admin',
  //Component alias
    name: 'admin',
  //Component name
    component: Admin,
}
2.Route attribute dynamic parameter transmission
this.$router.push({
        name:"/admin/${item.id}",
})
    ===receive this.$route.params.id===
    Note: the parameter is not visible, and the parameter value cannot be obtained after the page is refreshed
3 query Pass on reference
this.$router.push({
        name:"/admin",
     query:{id: item.id}
})

2) Vue route guard

Front routing guard
router.beforEach((to,from,next)=>{
    // To represents the information object of the route to be accessed
    // from represents the information object of the route to leave
    // The next() function indicates release
})

(3) Vue component value transfer

1 User defined attribute passed from parent to child
<Child-Vm :msg="msg"></Child-Vm>
<template>
    <div>
        <h1>{{msg}}</h1>
    </div>
</template>

<script>
    export default {
        props:['msg']
               
    }
</script>
2 Custom event of child transferring value to parent $emit(Event name, data)
<child @changeNum="getFromSon" class="er"></child>
 changeNumNew(){
            this.$emit('changeNum',this.msg)
        }
 getFromSon(val){
            this.fromSom = val
        }
3 Brother pass on value
 Create a bus.js Module and share one Vue Instance object
 At the sender, call bus.$emit(Event name, data to be sent)Trigger custom event
 On the receiving side, call bus.$on(Event name, event handler)Register custom events

(4) difference between watch and calculated

1. The functions that can be completed by computed can be realized by watch

2. The functions that can be implemented by both the watch and the computed may not necessarily be implemented. For example, the watch can perform asynchronous operations

Two small principles

1. The functions managed by Vue should be written as ordinary functions, so that this refers to the VM or component instance object

2 all functions not managed by vue (callback function of timer, callback function of Ajax, etc.) are best written as arrow functions

5 Vue life cycle

1 vue With 8 life cycles

beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforDestroy
destroyed
 Parent child component lifecycle relationship
 Creating: parent created --> son created --> son mounted --> father mounted
 Updating: parent beforeUpdate --> son beforeUpdate --> son updated --> father updated
 Destroy: parent beforeDestryy --> son beforeDestryy --> son destroyed --> father destroyed

2.What life cycle and sequence will be executed after entering the page or component
beforeCreate
created
beforeMount
mounted

3.At that stage, there were: $el,At that stage, there were: $data
created have data No, el
beforeMount have data No, el
mounted Both

4. If you join keep-alive,There will be two more life cycles
activated/deactivated

5. If you join keep-alive,What life cycles will be executed for the first time
beforeCreate
created
beforeMount
mounted
activated

6. If you join keep-alive,second
 Times or times n Which life cycles will be executed by the first entry
 Execute only one activated
7 Talk about your right keep-alive Understanding

1 vue A built-in component, cache component====>Improve performance

2 For example, the home page will jump to the details page, and repeated jump will not require repeated requests

(6) Vue routing mode

There are two routing modes::hash(default) history
1 Different manifestations 
history : http:/localhost:8080/about
hash : http:/localhost:8080/#/about
2.Jump request
history Will send a request
hash No request
3 After packaging, the front-end self-test shall be used hash,If used: history A blank page appears

(7) Vue data update view does not refresh

1 Modify the array value type and add new array members
 Method: add a new array
2 Add new objects in objects
 Solution: new object replacement
export default {
    data() {
        return {
            count: 0,
            colors: ['red', 'green', 'blue']
        }
    },
    methods: {
        changeValue() {
            setTimeout(() => {
                error
                this.colors[0] = 'apple'
                The first
                this.colors =  ['apple', 'green', 'blue']
                Second
                this.$set(this.colors,0,'apple')
            },500)
        }
    }
}
The best way $set The first parameter indicates that the data object can be: vue Instance object, or other objects
 The second parameter represents the property name
 The third parameter represents the attribute value

8 vue event binding $event

 <!--add No parameter transfer (default) e Native event object DOM
         Second add(The first parameter, $event) Interchangeable position
        -->
        <button @click="add">click</button>

add(e) {
            this.count += 1
            if(this.count % 2 === 0){
                e.target.style.backgroundColor = 'red'
            }else{
                 e.target.style.backgroundColor = ''
            }
            // console.log(e);

        }
2 Event modifier
e.preventDefault() Block default behavior
e.stopPropagation() Prevent foaming

9 vue event modifier

Event modifierexplain
.preventBlock default behavior (e.g. block a link jump, block form submission)
.stopPrevent event bubbling
.captureTrigger the current event handler in capture mode
.onceThe bound event is triggered only once
.selfThe event handler is triggered only when event.target is the current element itself

10 Vue v-module instruction modifier

Modifier effect
.numberAutomatically convert the value entered by the user to a numeric type
.lazyUpdate at 'change' instead of 'input'
.trimAutomatically filter the first and last blank characters entered by the user

11 Vue ref

operation dom
 Method element/Component definition ref
 Operation: $refs
<input type="text" v-if="inputVisible" @blur="showbtn" ref="myRef">
        <button v-else @click="showInp">Show text box</button>

 showInp() {
            // Lose focus
            this.inputVisible = true

            // Get focus $nexttick DOM callback after update

            this.$nextTick(() => {
                this.$refs.myRef.focus()
            })

        },
        showbtn() {
            this.inputVisible = false
        }

Global components

import Coutn from 'address'
vue.commponent('Component name',Coutn)
Call through label

Tags: Javascript Vue.js

Posted by Chris Powell on Tue, 23 Aug 2022 13:29:40 +0930