1. In VuecomputedandwatchPractical application of

1) about the watch

  • watchIs to monitor the change of a value, when the value changes, call its function block to make the corresponding operation, to achieve the effect of event monitoring
  • watchIs an object, so it defines a key-value pair, so the “key” is the name of the thing that needs to be listened on, and the “value” is the operation that needs to be done when the thing that needs to be listened on changes
  • watchthedeepAs well asimmediateattribute

When the deep attribute is not set, watch cannot monitor the change of an attribute value in an object in data. When monitoring is needed, the deep attribute should be set to monitor the object in depth. The immediate attribute determines whether to execute the handler function with the current initial value when the page is refreshed. In simple terms, whether to perform a listening operation at page rendering time, if set to true and otherwise not.

(2) on the computed

  • computedIt’s used to listen for variables that you definecomputedWhat is being listened on is defined in itself, not in data.
  • Once the variables are defined, they can be directly bound in both directions, compared towatchDeep listening,computedEasier to monitor. ,
  • computedGenerally, it is used by defaultgetterMethods are also providedsetterMethods.getterThat’s what’s called when you use this variable,setterIs called when assigning a value to a variable.
  • computedIt is cached, which means it is not called when the overall result is unchangedgettermethods

③ When to use Watch and when to use computed? (Personal understanding)

  • When a change in a variable can affect the change of multiple variables, it is preferredwatch
  • This parameter is preferred when multiple variable changes affect one variable changecomputed
  • Of course, some scenarios canwatchandcomputedIt is better to use in combination, so I won’t go into details

The following is the source code used to understand the relationship and characteristics. If you want to see the characteristics of computed caching, you can print some tags in the fullName listener and see that when you set the same value multiple times, the setter is called but the getter is not called. There is also a note in the code about the deep listening writing mode of watch.

<template>
  <div class="app-container">
    <div style="margin-bottom: 20px;">
      <el-input placeholder="First name (last name separated by a space)" class="name" type="text" v-model="name"></el-input>
      <el-button type="primary" @click="setName">Set up the</el-button>
    </div>

    <el-input placeholder="Language Results" class="score" type="number" v-model="grade.value1"></el-input>

    <el-input placeholder="Math scores." class="score" type="number" v-model="grade.value2"></el-input>

    <el-input placeholder="English scores" class="score" type="number" v-model="grade.value3"></el-input>

    <el-button type="primary" @click="sum">statistical</el-button>

    <div class="sum">
      <div>Name: {{lastName | | 'stay entry'}}</div>
      <div>Name: {{firstName | | 'stay entry'}}</div>
      <div>Total: {{result | | 0}}</div>
      <div>{{average}}</div>
      <div>{{highest}}</div>
      <div>{{lowest}}</div>
    </div>
    

  </div>
</template>

<script>
export default {
  computed: {fullName: {get: function(){
        return this.firstName + this.lastName
      },

      set: function(val){
        this.lastName = val.split(' ') [0]
        this.firstName = val.split(' ') [1]}},result(){
      let total = 0;
      this.score.forEach(item= > {
        total += Number(item);
      });
      return total
    }
  },
  
  watch: {
    // If you want to deeply listen on a value, the "key" is written with single quotation marks, for example, 'grade.value1':{handler(){... }}
    grade: {handler(val){
        this.highest = Math.max(this.grade.value1,this.grade.value2,this.grade.value3);
        this.lowest = Math.min(this.grade.value1,this.grade.value2,this.grade.value3)
      },
      deep: true.immediate: false
    },

    // when "value" is function, there are two arguments oldVal(newValue) and newValue(old value). When only one argument is written, the default is newVal
    result: function(val){
      this.average = (Number(val)/this.score.length).toFixed(2)}},data() {
    return {
      name:"".firstName: ' '.lastName: ' '.average: 0.highest: 0.lowest: 0.grade: {value1: 0.value2: 0.value3: 0,},score: []}},methods: {
    setName(){
      this.fullName = this.name
    },

    sum(){
      this.score = [this.grade.value1,this.grade.value2,this.grade.value3]
    }
  }
}
</script>

<style lang="scss" scoped>
.score..name{
  width: 30%;
  margin-right: 20px;
}
.sum{
  height: 50px;
  width: 60%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>
Copy the code

The @click event modifier in vue

  • .stopPrevents events from bubbling

<a v-on:click.stop="doThis"></a>

  • .preventPrevents the default behavior of events

<form v-on:submit.prevent="onSubmit"></form>

  • .captureEvents triggered by an inner element are handled here before they are passed on to the inner element for processing

<div v-on:click.capture="doThis">... </div>

  • .selfThe handler is fired only if the event.target is the current element itself

<div v-on:click.self="doThat">... </div>

Event.target always points to the DOM* that triggered the event itself

  • .onceThe click event fires only once

<a v-on:click.once="doThis"></a>

  • .passiveDo not intercept default events

<div v-on:scroll.passive="onScroll">... </div>

The default behavior of scroll events (scroll behavior) will be triggered immediately instead of waiting for onScroll execution to complete, improving mobile performance *

Something to watch out for

  • Modifiers can be used concatenated

V-on :click.self. Self blocks all clicks, whereas V-on :click.self. Prevent blocks only clicks on the element itself

  • Don’t put the.passive.preventUsed together,.preventIs ignored and the browser raises an error.

3, HTML DOM Document object querySelector()

Document. QuerySelector () returns the document to match the specified CSS selectors the first element of the document. The querySelectorAll () new method introduced in HTML 5, returns the document matching CSS selector list all the elements of the node

Other Document object methods

4. Common operations on arrays

① Some operations not detailed: Array.concat (),.join(),.push(),.pop(),.shift(),.unshitf(),.slice(),.splice(),.substr(),.substring(),.reverse(), .indexof (), lastIndexOf(),.map(),.foreach (),.toString()

②array.every() runs the given function on each item of the array, returning true for each item and false for each item

Array. some runs the given function on each item of the array, returning true for any item and false for any item

//array.every and array.some are clearly marked in red, one is "and", the other is "or"

function compare(element, index, array) {
 return element > 10;
}
[1.2.3.4.11].some(compare) //true
[1.2.3.4.11].some(compare) //false
Copy the code

④ Array.sort () sorts by Unicode code position, default ascending order

// If you need to customize collation rules, add collation functions
function sortFun(a,b){
 return a-b;
}
array.sort(sortFun())
Copy the code

⑤ Array.filter () runs the given function on each item of the array and returns the value that meets the function condition to form a new array without changing the original array

var words = ["spray"."limit"."elite"."exuberant"."destruction"."present"."happy"];

var longWords = words.filter(function(word){
 return word.length > 6;
});
// Filtered array longWords is ["exuberant", "destruction", "present"]
Copy the code

⑥array.find() passes a callback function that finds the first element in the array that matches the current search rule and terminates the search

Array.findindex () passes a callback function that finds the first element in the array that matches the current retrieval rule and terminates the retrieval

// The difference is to return an element or an element index
const arr = [1."2".3.3."2"]
console.log(arr.find(n= > typeof n === "number")) / / 1
console.log(arr.findIndex(n= > typeof n === "number")) / / 0
Copy the code

⑦ Array. fill(value, start, end) replaces the element in the array with a new element. Start and end are the start and end subscripts respectively. If this parameter is not set by default, each item is replaced. If the start index is set but the end index is not set, each item after the start index is replaced

⑧ Array.from () converts an array-like object to a real array

//String from the generated array
Array.from('foo'); <! - ['f'.'o'.'o'] - >Copy the code

For interesting uses of array.from (), check out this author’s article

⑨ array.reduce () takes a function as an accumulator, where each value in the Array (from left to right) is reduced to a single value, which is understood as an iterator over the Array, and returns a single value

Array.reduceright () is used in the same way, but starts from the end and proceeds

Array.reduce(), array.reduceright () do not perform callbacks on empty arrays

// Use instructions:
Array.reduce((acc, cur, idx, src) = > {}, initialValue)
ArrayThe callback function in.reduce() has four arguments and an initialValue that determines the initialValue of the accumulator (acc), which defaults to the first item in the source array (SRC) if not passedCopy the code

Acc: accumulator. If initialValue is passed in, the initial acc value is initialValue; if not, it is the first value of the array

Cur: current value.

Idx: indicates the current index. If initialValue is passed in, the index starts at 0, if not at 1

SRC: source array.

Example:

  • 1. Array items are accumulated or multiplied
// Test the array
arr: [1.2.3.4.5.6.7.8.9.10]

/ / accumulation
testReduce(){
 const result = this.arr.reduce((acc, current) = > {
    return acc + current;
 },0)}// result => 55

/ / multiplicative
testReduce(){
 const result = this.arr.reduce((acc, current) = > {
    return acc + current;
 },1)}// result => 3628800

Copy the code
  • 2, object array items summation
// Test the array
arr: [{count: 10.money: 1}, {count: 20.money: 2}, {count: 30.money: 3}]

//count, weight accumulates
testReduce(){
 this.result = this.arr.reduce((acc, current) = > {
   for(let key in current){
     if(! acc[key]){ acc[key] =0;
     }
     acc[key] += current[key]
   }
   return acc
 },{})
} // result => { "count": 60, "money": 6 }

Copy the code
  • In addition, changing the logic of the callback function can also realize the conversion of two-dimensional arrays to one-dimensional arrays, counting the number of occurrences of elements, counting the most occurrences of elements, array de-duplication (can be de-duplication of strings), calculating cartesian products and other operations
// Common array decrement
let arr = [1.3.3.2.4.4.5.3.2.5.6]
let newArr = arr.reduce((acc, cur) = > {
 if(! acc.includes(cur)) { acc.push(cur) }return acc
}, [])
console.log(newArr) // (6) [1, 3, 2, 4, 5, 6]

// Object array deduplicates. Object array deduplicates specify which object attribute to deduplicate
let arr1 = [{
 name: 'Joe'.age: 18
}, {
 name: 'Joe'.age: 18
}, {
 name: 'bill'.age: 20
}, {
 name: 'Cathy'.age: 20
}, {
 name: 'bill'.age: 22
}, {
 name: 'six sun'.age: 22
}]
function doRepeat (arr, key) {
 let obj = {}
 let newArr1 = arr.reduce((acc, cur) = > {
   if(! obj[cur[key]]) { obj[cur[key]] = cur[key] acc.push(cur) }return acc
 }, [])
 return newArr1
}
// Delete the name
console.log(doRepeat(arr1, 'name'))
// 0: {name: "zhang3 ", age: 18}
// 1: {name: "li ", age: 20}
// 2: {name: "wang ", age: 20}
// 3: {name: "sun ", age: 22}
Copy the code

⑩Array.entries() and array.keys () both iterate over an Array and return a new Array iterator object. Array.entries() returns key/value pairs, whereas array.keys () returns only index keys

There is a next() method on array.entries () that is called to obtain the key-value pairs of the original Array

The output is also iterated if the array element is null

  • Array. Entries () is used
var arr = ["a"."b"."c"];
var iter = arr.entries();
var a = [];

// for(var i=0; i< arr.length; I++){// this is what is actually used
for(var i=0; i< arr.length+1; i++){    // Note that length+1 is larger than the array length
   var tem = iter.next();             // Update next with each iteration
   console.log(tem.done);             // We can see that done is false after update
   if(tem.done ! = =true) {Done is true when iterating through the iterator
       console.log(tem.value); a[i]=tem.value; }}console.log(a);                         // After traversing, print an array of next. Value
Copy the code
  • Array. The keys () is used
const array1 = ['a'.'b'.'c'];
const iterator = array1.keys();

for (const key of iterator) {
 console.log(key);
}
// console prints => 0,1,2
Copy the code