vue entry notes (entry notes for novices)

Keywords: Vue Javascript Attribute Programming

Vue Day 02

Article directory

1, ES6 syntax supplement

1.1.let/var (define variable)

  1. let can be seen as a more perfect var
  2. Block level scope
  3. In javascript, if and for have no scope as long as the function has
    • var in ES5 has no block level scope (if/for)
    • let in ES6 has block level effect (if/for)
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
<button>Button 4</button>
<button>Button 5</button>
<script>
  // 1. Variable scope: the range in which the variable is available
  // {
  //   var name = 'why';
  //   console.log(name);
  // }
  // console.log(name);
  //It will print here. why has jumped out of the range
  
  // 2. No problem caused by block level scope: block level of if
  // var func;
  // if (true) {
  //   var name = 'why';
  //   func = function () {
  //     console.log(name);
  //   }
  //   // func()
  // }
  // name = 'kobe'
  //The value of name has been modified outside. When the fun function is called again, the value has changed

  var name = 'why'
  function abc(bbb) { // bbb = 'why'
    console.log(bbb);
  }
  abc(name)
  name = 'kobe'
  //Here bbb in the function has its own scope and has no relationship with the outside. Changing the value of name again will not affect the printing result
  //Understanding of formal parameter and actual parameter
  
  // 3. No problem caused by block level scope: block level of for
  // Why closures can solve problems: functions are a scope
  // var btns = document.getElementsByTagName('button');
  // for (var i=0; i<btns.length; i++) {
  //   (function (i ) { // 0
  //     btns[i].addEventListener('click', function () {
  //       console.log('the '+ i +' button is clicked ');
  //     })
  //   })(i)
  // }
  
  // The functions in ES5 are called five times, and the subsequent calls will cause the previous i to change
  //i in a closure has nothing to do with i outside
  
  const btns = document.getElementsByTagName('button')
  for (let i = 0; i < btns.length; i++) {
    btns[i].addEventListener('click', function () {
      console.log('The first' + i + 'Buttons clicked');
    })
  }
 
  // //ES6 has also called five times, but each time i is different, the later call will not change the value of the previous i
</script>

Conclusion:

  1. Before ES5, because if and for had no concept of block level scope, we had to use function scope to solve the problem of applying external variables
  2. In ES6, let is added. Let is a block level scope with if and for. It has scope in itself, so you don't need to use closures to solve problems
  3. There is no block level scope, that is to say, a variable i defined by var can be modified elsewhere (it can be understood by global variables and member variables in java)
  4. All in all, it's better to use let

1.2.const

  • In many languages, such as C/C + +, the main function is to modify a variable into a constant
  • In JavaScript, the identifier decorated with const is constant and cannot be assigned again
  • const can be used to ensure the security of data when the decorated identifier is not reassigned
<script>
  // 1. Note 1: once the identifier modified by const is assigned, it cannot be modified
  // const name = 'why';
  // name = 'abc';
  // 2. Note 2: when const is used to define an identifier, an assignment must be made
  // const name;
  // 3. Note 3: a constant means that the object it points to cannot be modified, but the internal properties of the object can be changed
  const obj = {
    name: 'why',
    age: 18,
    height: 1.88
  }
  // obj = {}
  console.log(obj);
  obj.name = 'kobe';
  obj.age = 40;
  obj.height = 1.87;
  console.log(obj);
</script>

Why are the results the same twice?
After const modification, the memory address that the pointer points to will not change. It points to that memory all the time, but the value in it can be modified, because the point has not changed, but the content has changed.
When the contents change, the value in the memory changes. As for why it is the same, I don't know that hahahaha feels like the reason for loading

1.3. Object enhanced writing

<script>
  // const obj = new Object()
  // const obj = {
  //   name: 'why',
  //   age: 18,
  //   run: function () {
  //     console.log('running ');
  //   },
  //   eat: function () {
  //     console.log('next thing ');
  //   }
  // }
  
  // 1. Enhanced attribute writing
  const name = 'why';
  const age = 18;
  const height = 1.88
  
  // The way to write ES5
  // const obj = {
  //   name: name,
  //   age: age,
  //   height: height
  // }
  
  // const obj = {
  //   name,
  //   age,
  //   height,
  // }
  //
  // console.log(obj);
  
  // 2. Enhanced writing of functions
  // The way to write ES5
  // const obj = {
  //   run: function () {
  //
  //   },
  //   eat: function () {
  //
  //   }
  // }
  const obj = {
    run() {
    },
    eat() {
    }
  }
</script>

2, Event monitoring

  • Basic use of v-on
    Role: bind event listener
    Abbreviation: @
    Expected: Function | Inline Statement | Object
    Parameter: event
<div id="app">
  <h2>{{counter}}</h2>
  <!--<h2 v-bind:title></h2>-->
  <!--<h2 :title></h2>-->
  <!--<button v-on:click="counter++">+</button>-->
  <!--<button v-on:click="counter&#45;&#45;">-</button>-->
  <!--<button v-on:click="increment">+</button>-->
  <!--<button v-on:click="decrement">-</button>-->
  <button @click="increment">+</button>
  <button @click="decrement">-</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      counter: 0
    },
    methods: {
      increment() {
        this.counter++
      },
      decrement() {
        this.counter--
      }
    }
  })
</script>
  • The parameter problem of v-on
  1. If the method doesn't need extra parameters, the () after the method can not be added
    But note: if the method itself has a parameter, the native event event parameter will be passed in by default
  2. If you need to pass in a parameter at the same time and need event at the same time, you can pass in the event through $event.
<div id="app">
  <!--1.Event called method has no parameters-->
  <button @click="btn1Click()">Button 1</button>
  <button @click="btn1Click">Button 1</button>
  <!--2.When the event is defined, Parentheses are omitted when writing methods, But the method itself needs a parameter, This time, Vue The browser will be generated by default event Event object passed in as parameter to method-->
  <!--<button @click="btn2Click(123)">Button 2</button>-->
  <!--<button @click="btn2Click()">Button 2</button>-->
  <button @click="btn2Click">Button 2</button>
  <!--3.Method definition, We need event object, At the same time, other parameters are needed-->
  <!-- In call mode, How to get the browser parameters manually event object: $event-->
  <button @click="btn3Click(abc, $event)">Button 3</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'How do you do',
      abc: 123
    },
    methods: {
      btn1Click() {
        console.log("btn1Click");
      },
      btn2Click(event) {
        console.log('--------', event);
      },
      btn3Click(abc, event) {
        console.log('++++++++', abc, event);
      }
    }
  })
  // If the function requires parameters but does not pass in, the parameter of the function is undefined
  // function abc(name) {
  //   console.log(name);
  // }
  //
  // abc()
</script>

  • Modifier for v-on
  1. stop - call event.stopPropagation().
  2. prevent - call event.preventDefault().
  3. {keyCode | keyAlias} - triggers the callback only if the event is triggered from a specific key.
  4. Native - listens for native events on the component root element.
  5. Once - triggers the callback only once.
<div id="app">
  <!--1. .stop Use of modifiers-->
  <div @click="divClick">
    aaaaaaa
    <button @click.stop="btnClick">Button</button>
  </div>
  <!--2. .prevent Use of modifiers-->
  <br>
  <form action="baidu">
    <input type="submit" value="Submission" @click.prevent="submitClick">
  </form>
  <!--3. .Monitor the key cap of a keyboard-->
  <input type="text" @keyup.enter="keyUp">
  <!--4. .once Use of modifiers-->
  <button @click.once="btn2Click">Button 2</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'How do you do'
    },
    methods: {
      btnClick() {
        console.log("btnClick");
      },
      divClick() {
        console.log("divClick");
      },
      submitClick() {
        console.log('submitClick');
      },
      keyUp() {
        console.log('keyUp');
      },
      btn2Click() {
        console.log('btn2Click');
      }
    }
  })
</script>
  1. In case 1, if there is no. stop button, divClick and btnClick will be printed. If bubble is prevented after adding, divClick will not be printed
  2. Case 2 will not be submitted directly. It can be customized
  3. Case 3 is keyboard click, which is triggered only by pressing enter
  4. Case 4 Click event will only be executed once

3, Condition judgment

3.1.1. Introduction to if basic syntax

  • v-if
  • v-else-if
  • v-else
    Control display
<div id="app">
  <h2 v-if="isShow">
    <div>abc</div>
    <div>abc</div>
    {{message}}
  </h2>
  <h1 v-else>isShow by false Time, Show me</h1>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'How do you do',
      isShow: true
    }
  })
</script>
<div id="app">
  <h2 v-if="score>=90">excellent</h2>
  <h2 v-else-if="score>=80">good</h2>
  <h2 v-else-if="score>=60">pass</h2>
  <h2 v-else>Fail,</h2>
  <h1>{{result}}</h1>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      score: 99
    },
    computed: {
      result() {
        let showMessage = '';
        if (this.score >= 90) {
          showMessage = 'excellent'
        } else if (this.score >= 80) {
          showMessage = 'good'
        }
        // ...
        return showMessage
      }
    }
  })
</script>

v-else-if can directly choose to calculate attributes instead of using less

3.1.2. case

When users log in again, they can switch whether to log in with user account or email address
(for in the label means that the input box will focus after clicking the user account.)

<div id="app">
  <span v-if="isUser">
    <label for="username">User account</label>
    <input type="text" id="username" placeholder="User account">
  </span>
  <span v-else>
    <label for="email">User mail box</label>
    <input type="text" id="email" placeholder="User mail box">
  </span>
  <button @click="isUser = !isUser">Switching type</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      isUser: true
    }
  })
</script>


Problem: the last content is still not covered after clicking switch

Reason: vue will merge two able tags and input tags, resulting in the user account and user mailbox sharing one
Solution: add a key to the input tag to indicate that the two are different, and vue will not merge

<input type="text" id="username" placeholder="User account" key="username">
<input type="text" id="email" placeholder="User mail box" key="email">

3.1.3. Use of v-show

<div id="app">
  <!--v-if: When conditions are false Time, Contain v-if Element of instruction, It doesn't exist dom in-->
  <h2 v-if="isShow" id="aaa">{{message}}</h2>
  <!--v-show: When conditions are false Time, v-show Just add an inline style to our element: display: none-->
  <h2 v-show="isShow" id="bbb">{{message}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      message: 'How do you do',
      isShow: true
    }
  })
</script>

  1. v-if when the condition is false, there will be no corresponding element in DOM at the root.
  2. v-show when the condition is false, it just sets the display attribute of the element to none.

How to choose in development?

  • When you need to slice between display and hide frequently, use v-show
  • When there is only one switch, by using v-if

4, Loop traversal

4.1.1. Loop through array

<div id="app">
  <!--1.In the process of traversal,Index value not used(Subscript value)-->
  <ul>
    <li v-for="item in names">{{item}}</li>
  </ul>
  <!--2.In the process of traversal, Get index value-->
  <ul>
    <li v-for="(item, index) in names">
      {{index+1}}.{{item}}
    </li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      names: ['why', 'kobe', 'james', 'curry']
    }
  })
</script>

4.1.2. Loop through objects

<div id="app">
  <!--1.In the process of traversing objects, If you just get a value, So what we get is value-->
  <ul>
    <li v-for="item in info">{{item}}</li>
  </ul>
  <!--2.Obtain key and value format: (value, key) -->
  <ul>
    <li v-for="(value, key) in info">{{value}}-{{key}}</li>
  </ul>
  <!--3.Obtain key and value and index format: (value, key, index) -->
  <ul>
    <li v-for="(value, key, index) in info">{{value}}-{{key}}-{{index}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      info: {
        name: 'why',
        age: 18,
        height: 1.88
      }
    }
  })
</script>

4.1.3. Add key during the cycle


Need to guarantee the uniqueness of key

<div id="app">
  <ul>
    <li v-for="item in letters" :key="item">{{item}}</li>
  </ul>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      letters: ['A', 'B', 'C', 'D', 'E']
    }
  })
</script>

4.1.3. Response method in array

  • push() -- add an element at the end
  • pop() -- delete the last element in the array
  • shift() -- delete the first element in the array
  • unshift() --- add elements at the front of the array
  • splice() -- delete element / insert element / replace element
    Delete elements: the second parameter is passed in. You need to delete several elements (if not, delete all the following elements)
    Replace element: the second parameter indicates that we want to replace several elements, followed by the element to replace the previous one
    Insert element: second parameter, passing in 0, followed by the element to insert
  • sort() -- traversing elements in an array
  • reverse() -- flip elements in an array
<div id="app">
  <ul>
    <li v-for="item in letters">{{item}}</li>
  </ul>
  <button @click="btnClick">Button</button>
</div>
<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      letters: ['a', 'b', 'c', 'd']
    },
    methods: {
      btnClick() {
        // 1.push method
        // this.letters.push('aaa')
        // this.letters.push('aaaa', 'bbbb', 'cccc')
        
        // 2.pop(): delete the last element in the array
        // this.letters.pop();
        
        // 3.shift(): delete the first element in the array
        // this.letters.shift();
        
        // 4.unshift(): add elements at the top of the array
        // this.letters.unshift()
        // this.letters.unshift('aaa', 'bbb', 'ccc')
        
        // 5. Role of splice: delete element / insert element / replace element
        // Delete elements: the second parameter is passed in. You need to delete several elements (if not, delete all the following elements)
        // Replace element: the second parameter indicates that we want to replace several elements, followed by the element to replace the previous one
        // Insert element: second parameter, passing in 0, followed by the element to insert
        // splice(start)
        // splice(start):
        this.letters.splice(1, 3, 'm', 'n', 'l', 'x')
        // this.letters.splice(1, 0, 'x', 'y', 'z')
        // 5.sort()
        // this.letters.sort()
        
        // 6.reverse()
        // this.letters.reverse()
        
        // Note: modify the elements in the array by index value
        // this.letters[0] = 'bbbbbb';
        // this.letters.splice(0, 1, 'bbbbbb')
        // Set (object to be modified, index value, modified value)
        // Vue.set(this.letters, 0, 'bbbbbb')
      }
    }
  })
</script>

5, Book shopping cart case

  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
<div id="app">
  <div v-if="books.length">
    <table>
      <thead>
      <tr>
        <th></th>
        <th>Titles of books</th>
        <th>Publication date</th>
        <th>Price</th>
        <th>Purchase quantity</th>
        <th>operation</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, index) in books">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.date}}</td>
        <td>{{item.price | showPrice}}</td>
        <td>
          <button @click="decrement(index)" v-bind:disabled="item.count <= 1">-</button>
          {{item.count}}
          <button @click="increment(index)">+</button>
        </td>
        <td><button @click="removeHandle(index)">remove</button></td>
      </tr>
      </tbody>
    </table>
    <h2>Total price: {{totalPrice | showPrice}}</h2>
  </div>
  <h2 v-else>Shopping cart is empty</h2>
</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>
<script>
</script>
</body>
</html>
  • main.js
const app = new Vue({
  el: '#app',
  data: {
    books: [
      {
        id: 1,
        name: '<Introduction to Algorithms',
        date: '2006-9',
        price: 85.00,
        count: 1
      },
      {
        id: 2,
        name: '<UNIX Programming art',
        date: '2006-2',
        price: 59.00,
        count: 1
      },
      {
        id: 3,
        name: '<Programming Abas',
        date: '2008-10',
        price: 39.00,
        count: 1
      },
      {
        id: 4,
        name: '<Code Encyclopedia',
        date: '2006-3',
        price: 128.00,
        count: 1
      },
    ]
  },
  methods: {
    // getFinalPrice(price) {
    //   return '¥' + price.toFixed(2)
    // }
    increment(index) {
      this.books[index].count++
    },
    decrement(index) {
      this.books[index].count--
    },
    removeHandle(index) {
      this.books.splice(index, 1)
    }
  },
  computed: {
    totalPrice() {
      let totalPrice = 0
      for (let i = 0; i < this.books.length; i++) {
        totalPrice += this.books[i].price * this.books[i].count
      }
      return totalPrice
      // for (let i in/of this.books)
      // reduce
    }
  },
  filters: {
    showPrice(price) {
      return '¥' + price.toFixed(2)
    }
  }
})
  • style.css
table {
  border: 1px solid #e9e9e9;
  border-collapse: collapse;
  border-spacing: 0;
}
th, td {
  padding: 8px 16px;
  border: 1px solid #e9e9e9;
  text-align: left;
}
th {
  background-color: #f7f7f7;
  color: #5c6b77;
  font-weight: 600;
}

Published 2 original articles, praised 0 and visited 13
Private letter follow

Posted by runestation on Sun, 15 Mar 2020 03:16:35 -0700