current position:Home>Vue basic grammar

Vue basic grammar

2022-05-15 02:47:50@The road of youth


 Insert picture description here

One . Interpolation operations

1.Mustache grammar

 Insert picture description here

2.v-once Use of instructions

 Insert picture description here
Be careful

  • This command is followed by You don't need to follow any expression .
  • This instruction represents elements and components Render only once , It doesn't change with the data .

3.v-html Use of instructions

 Insert picture description here

4.v-text Use of instructions

 Insert picture description here
v-text Instructions and Mustache Grammar comparison :

Both display data in the interface , however v-text No, Mustache Grammar is flexible , In the diagram above , We can see ,v-text The instruction overwrites the value in the original label . In the scene of string splicing ,v-text Instructions will no longer be suitable for .

5.v-pre Use of instructions

 Insert picture description here

6.v-cloak Use of instructions

 Insert picture description here

Two . Dynamic binding properties

1.v-bind Basic use of

 Insert picture description here
v-bind Grammar sugar writing ( Abbreviation ): Use it directly : Property name that will do .

2.v-bind Dynamic binding class

Object syntax

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style type="text/css"> .active {
      color: red; } </style>
</head>
<body>
<div id="app">
  <!-- The property value is a string -->
  <h2 :class="active">{
   {message}}</h2>
  <!-- Property value is an object -->
  <!--<h2 :class="{key1: value1, key2: value2}">{
    {message}}</h2>-->
  <!--<h2 :class="{ Class name 1: boolean,  Class name 2: boolean}">{
    {message}}</h2>-->
  <!--<h2 class="title" :class="{active: isActive, line: isLine}">{
    {message}}</h2>-->
  <h2 class="title" :class="getClasses()">{
   {message}}</h2>
  <button v-on:click="click"> Click to switch colors </button>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      message: 'Hello', active: 'active', isActive: true, isLine: true }, methods: {
      click: function () {
      this.isActive = !this.isActive; }, getClasses: function () {
      return {
     active: this.isActive, line: this.isLine}; } } }) </script>
</body>
</html>

 Insert picture description here
Array syntax
 Insert picture description here

2.v-bind Dynamic binding style

Object syntax
 Insert picture description here
Array syntax
 Insert picture description here

3、 ... and . Compute properties

1. The basic use of computational properties

 Insert picture description here
Usage scenarios for calculating attributes : When we need to convert the data, we can display , Or when you need to combine multiple data for display , We can use computational properties to process .

2. Complex operation of calculating attributes

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <h2> Total price :{
   {totalPrice}}  element </h2>
</div>


<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      books: [ {
     id: 1001, name: 'Linux Development ', price: 58}, {
     id: 1002, name: ' Software Testing Technology ', price: 42}, {
     id: 1003, name: ' Software project management ', price: 60}, ] }, computed: {
      totalPrice: function () {
      let result = 0; for (let i=0; i<this.books.length; i++) {
      result += this.books[i].price; } return result; } } }) </script>

</body>
</html>

3. Computed attribute setter and getter

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <h2>{
   {fullName}}</h2>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      firstName: ' Crown prince ', lastName: ' Highness !' }, computed: {
      /*fullName: function () { return this.firstName + ' ' + this.lastName; }*/ fullName: {
      set: function (newValue) {
      let names = newValue.split(' '); this.firstName = names[0]; this.lastName = names[1]; }, get: function () {
      return this.firstName + ' ' + this.lastName; } } } }) </script>

</body>
</html>

 Insert picture description here

4. Compute properties and methods Comparison of

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <!--1. Directly joining together -->
  <!--<h2>{
    {firstName}} {
    {lastName}}</h2>-->
  <!--2. Use methods-->
  <h2>{
   {getFullName()}}</h2>
  <h2>{
   {getFullName()}}</h2>
  <h2>{
   {getFullName()}}</h2>
  <h2>{
   {getFullName()}}</h2>

  <hr>
  <!--3. Use calculated properties -->
  <h2>{
   {fullName}}</h2>
  <h2>{
   {fullName}}</h2>
  <h2>{
   {fullName}}</h2>
  <h2>{
   {fullName}}</h2>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      firstName: ' Crown prince ', lastName: ' Highness ' }, methods: {
      getFullName: function () {
      console.log('getFullName'); return this.firstName + ' ' + this.lastName; } }, computed: {
      fullName: function () {
      console.log('fullName'); return this.firstName + ' ' + this.lastName; } } }) </script>

</body>
</html>

Computing properties are cached , If used more than once , The calculated property will only be called once .
 Insert picture description here

Four . Event monitoring

1.v-on Basic use of

 Insert picture description here
v-on:click The grammar of sugar @click.

2.v-on The parameter problem of

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>


<div id="app">
  <!--1. When there are no parameters ,() Don't write -->
  <button @click="btn1Click"> Button 1</button>
  <!--2. When you don't pass parameters , The browser will help us pass a event-->
  <button @click="btn2Click"> Button 2</button>
<!-- <button @click="btn2Click(666)"> Button 2</button>-->
  <!--3. Both pass ordinary parameters , Also pass on event-->
  <button @click="btn3Click(num, $event)"> Button 3</button>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      message: 'Hello', num: 888 }, methods: {
      btn1Click() {
      console.log('btn1 By clicking the '); }, btn2Click(num) {
      console.log('btn2 By clicking the ---->' + num); }, btn3Click(num, event) {
      console.log(num + '----------' + event); } } }) </script>

</body>
</html>

 Insert picture description here

3.v-on The embellishment of

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <!--1. Use .stop Stop bubbling -->
  <div @click="divClick">
    aaa
    <button @click.stop="btnClick"> Button </button>
  </div>
  <!--2. Use .prevent Blocking default behavior -->
  <form action="baidu">
    <input type="submit" @click.prevent="submitClick">
  </form>

  <!--3. Decorate the keyboard pop-up event -->
  <input type="text" @keyup.enter="inputClick">

  <br>
  <button @click.once="btn1Click"> Only the first click of the effective button </button>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      message: 'Hello' }, methods: {
      divClick() {
      console.log('divClick'); }, btnClick() {
      console.log('btnClick'); }, submitClick() {
      console.log('submitClick'); }, inputClick() {
      console.log('inputClick'); }, btn1Click() {
      console.log('btn1Click'); } } }) </script>

</body>
</html>

 Insert picture description here

5、 ... and . conditional

1.v-if、v-else and v-else-if Use

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <h2 v-if="score>90"> good </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: 92 }, computed: {
      result() {
      let newScore = this.score; let result = ''; if (newScore>90) {
      result = ' good '; }else if (newScore>80) {
      result = ' good '; }else if (newScore>60) {
      result = ' pass '; }else {
      result = ' fail, '; } return result; } } }) </script>

</body>
</html>

 Insert picture description here

2. Small case of login mode switching

 Insert picture description here
problem : If we have input , Switched types , We will find that the text still displays the previous input ?

analysis : This is because Vue It's going on DOM When rendering , For performance reasons , Reuse existing elements as much as possible , Instead of recreating new elements . In the case above ,Vue The original will be found inside input Element is no longer used , Act directly as else Medium input To use .

Solution : If we don't want Vue There are similar reuse problems , You can give the corresponding input add to key. And we need to make sure key Different .
 Insert picture description here

3.v-show Use of instructions

 Insert picture description here
v-show and v-if The difference between :
v-if When conditions are false when , There won't be a corresponding element at all DOM in .
v-show When conditions are false when , It's just that the elements are display Property is set to none nothing more .

How to choose in development ?
When you need to switch between show and hide frequently , Use v-show.
When there is only one switch , By using v-if.

6、 ... and . Loop traversal

1.v-for Traversal array

 Insert picture description here

2.v-for Traversing objects

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <!--1. Only traverse the value of the object -->
  <ul>
    <li v-for="item in student">{
   {item}}</li>
  </ul>
  <!--2. Objects everywhere key and value-->
  <ul>
    <li v-for="(value, key) in student">{
   {value}}--{
   {key}}</li>
  </ul>
  <!--3. Traversing objects key、value And index -->
  <ul>
    <li v-for="(value, key, index) in student">{
   {value}}--{
   {key}}--{
   {index+1}}</li>
  </ul>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      student: {
      name: ' Highness ', aga: 22, sex: ' male ', score: 98 } } }) </script>


</body>
</html>

 Insert picture description here

3.v-for Use the procedure to add key

 Insert picture description here
key The main purpose is to update the virtual environment efficiently DOM.

4. Responsive and non responsive methods in arrays

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

<div id="app">
  <ul>
    <li v-for="letter in letters">{
   {letter}}</li>
    <button @click="btnClick"> Button </button>
  </ul>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      letters: ['A', 'B', 'C', 'D', 'E'] }, methods: {
      btnClick() {
      //1.push() Method   Add one or more elements at the end of the array  /*this.letters.push('F');*/ //2.pop() Method   Delete one or more elements from the last of the array  /*this.letters.pop();*/ //3.unshift() Method   Add one or more elements to the front of the array  /*this.letters.unshift('aaa', 'bbb');*/ //4.shift() Method   Remove the element from the front of the array  /*this.letters.shift();*/ //5.splice() Method  /*this.letters.splice(1, 2); // Remove elements  */ /*this.letters.splice(1, 2, 'bb', 'cc'); // Replacement elements */ /* this.letters.splice(1, 0, 'bb'); // Insert elements */ //6.sort() Method  /*this.letters.sort();*/ //7.reverse() Method  /*this.letters.reverse();*/ // Be careful : Modifying the value in an array element is not responsive  /*this.letters[1] = 'bbb';*/ /*this.letters.splice(1, 1, 'bb');*/ Vue.set(this.letters, 1, 'bb'); } } }) </script>

</body>
</html>

Be careful : When the value of an element in the array is modified , The value of the corresponding page is not modified .

5. Click the mouse to switch the color of small cases

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style> .active {
      color: red; } </style>
</head>
<body>

<div id="app">
  <ul>
    <li v-for="(movie, index) in movies" :class="{active: currentIndex === index}" @click="liClick(index)">{
   {index}} {
   {movie}}</li>
  </ul>
</div>

<script src="../js/vue.js"></script>
<script> const app = new Vue({
      el: '#app', data: {
      movies: [' Chinatown detective ', ' Fast and furious ', ' Pirates of the Caribbean ', ' True colour of a hero '], currentIndex: 0 }, methods: {
      liClick(index) {
      this.currentIndex = index; } } }) </script>
</body>
</html>

7、 ... and . 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">
  <table cellpadding="0" cellspacing="0" width="500px" height="300px">
    <thead>
      <tr align="center" style="background: rgba(0,0,0,0.1);">
        <th></th>
        <th> Book name </th>
        <th> Publication date </th>
        <th> Price </th>
        <th> Purchase quantity </th>
        <th> operation </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(book,index) in books" align="center">
        <td width="60px">{
   {book.id}}</td>
        <td>{
   {book.name}}</td>
        <td>{
   {book.date}}</td>
        <!-- Use filters -->
        <td>{
   {book.price | showPrice}}</td>
        <td>
          <button @click="decrement(index)" :disabled="book.count <= 1">-</button>
          {
   {book.count}}
          <button @click="increment(index)">+</button>
        </td>
        <td width="60px"><button @click="deleteOne(index)"> remove </button></td>
      </tr>
    </tbody>

  </table>

  <br>
  <button @click="clear()"> empty cart </button>
  <h2> Total price :{
   {totalPrice | showPrice}}</h2>

  <h2 v-show="books.length === 0" style="color: red"> Currently there are no books in the shopping cart !</h2>

</div>
<script src="../js/vue.js"></script>
<script src="main.js"></script>

</body>
</html>

style.css

tr td,th {
    
  border: 1px solid rgba(0,0,0,0.2);
}
table {
    
  border: 1px solid rgba(0,0,0,0.2);
}

main.js

var app = new Vue({
    
  el: '#app',
  data: {
    
    books: [{
    
      id: 1,
      name: '《 Introduction to algorithms 》',
      date: '2006-9',
      price: 85,
      count: 1
    },
    {
    
      id: 2,
      name: '《UNIX Programming art 》',
      date: '2006-2',
      price: 59,
      count: 1
    },
    {
    
      id: 3,
      name: '《 Programming pearls 》',
      date: '2008-10',
      price: 39,
      count: 1
    },
    {
    
      id: 4,
      name: '《 The code of 》',
      date: '2006-3',
      price: 128,
      count: 1
    },
    ]
  },
  computed: {
    
    totalPrice() {
    
      var totalPrice = 0;
      for (var i=0; i < this.books.length; i++) {
    
        totalPrice =  totalPrice + (this.books[i].count) * (this.books[i].price);
      }
      return totalPrice;
    }
  },
  methods: {
    
    // Reduce the number of books 
    decrement(index) {
    
      this.books[index].count--;
    },
    // Increase the number of books 
    increment(index) {
    
      this.books[index].count++;
    },
    // Delete a Book 
    deleteOne(index) {
    
      var conf = confirm(" Are you sure to delete ?");
      if (conf == true) {
    
        this.books.splice(index, 1);
      }
    },
    // Empty all books 
    clear() {
    
      var clear = confirm(' Are you sure to empty the shopping cart ? This operation cannot be undone after confirmation !');
      if (clear) {
    
        this.books.splice(0, this.books.length);
      }
    }
  },
  filters: {
    
    showPrice(price) {
    
      return '¥' + price.toFixed(2);
    }
  }
})

Effect demonstration
 Insert picture description here

8、 ... and .v-model Use of instructions

1.v-model Basic use of

 Insert picture description here
 Insert picture description here

2.v-model Principle

 Insert picture description here

About v-model The internal principle ,Vue The official website of gives the following explanation : Insert picture description here

3.v-model combination radio type

 Insert picture description here

4.v-model combination checkbox type

checkbox The radio

 Insert picture description here

checkbox multi-select

 Insert picture description here

More practical operation

 Insert picture description here

5.v-model combination select type

 Insert picture description here

6.v-model Use of modifiers

 Insert picture description here

copyright notice
author[@The road of youth],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/132/202205120516072567.html

Random recommended