Vue Learning Day2 - Instruction Supplement

1. Instruction modifiers

1. What is an instruction modifier?

​ The so-called instruction modifier is to specify some instruction suffixes through "." Different suffixes encapsulate different processing operations—> Simplify the code

2. Key modifiers

  • @keyup.enter —> Triggered when the enter key is clicked

Code demo:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./css/index.css" />
    <title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
    <!-- 输入框 -->
    <header class="header">
        <h1>小凯的记事本</h1>
        <input v-model:id="toName" @keyup.enter="add" placeholder="请输入任务" class="new-todo" />
        <button @click="add" class="add">添加任务</button>
    </header>
    <!-- 列表区域 -->
    <section class="main">
        <ul class="todo-list">
            <li class="todo" v-for="(item,index) in list" :key="item.id">
                <div class="view">
                    <span class="index">{
   
   { index + 1 }}.</span> <label>{
   
   { item.name }}</label>
                    <button class="destroy" @click="del(item.id)"></button>
                </div>
            </li>
        </ul>
    </section>
    <!-- 统计和清空 -->
    <footer class="footer" v-show="list.length > 0">
        <!-- 统计 -->
        <span class="todo-count">合 计:<strong> {
   
   { list.length }}</strong></span>
        <!-- 清空 -->
        <button class="clear-completed" @click="clear">
            清空任务
        </button>
    </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>

    const app = new Vue({
      
      
        el: '#app',
        data: {
      
      
            toName: '',
            list: [
                {
      
      id: 1,name: '微服务学习'},
                {
      
      id: 2,name: 'SpringBoot从入门到精通'},
                {
      
      id: 3,name: 'SpringCloud'}
            ]
        },
        methods: {
      
      
            del(id){
      
      
                this.list = this.list.filter(item => item.id !== id)
            },
            add(){
      
      
                if (this.toName.trim()=== ''){
      
      
                    alert('请输入内容')
                    return
                }
                this.list.unshift({
      
      
                    id: +new Date(),
                    name: this.toName
                })
                this.toName=''
            },
            clear(){
      
      
                   this.list=[]
            }
        }
    })

</script>
</body>
</html>

3. v-model modifier

  • v-model.trim —> remove the first space
  • v-model.number —> turn the number

4. Event modifiers

  • @event name.stop —> stop bubbling
  • @EventName.prevent —> prevent the default behavior
  • @event name.stop.prevent —> can be used in conjunction to prevent event bubbling and default behavior
 <style>
    .father {
      
      
      width: 200px;
      height: 200px;
      background-color: pink;
      margin-top: 20px;
    }
    .son {
      
      
      width: 100px;
      height: 100px;
      background-color: skyblue;
    }
  </style>

 <div id="app">
    <h3>v-model修饰符 .trim .number</h3>
    姓名:<input v-model="username" type="text"><br>
    年纪:<input v-model="age" type="text"><br>

    
    <h3>@事件名.stop     →  阻止冒泡</h3>
    <div @click="fatherFn" class="father">
      <div @click="sonFn" class="son">儿子</div>
    </div>

    <h3>@事件名.prevent  →  阻止默认行为</h3>
    <a @click href="http://www.baidu.com">阻止默认行为</a>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      
      
      el: '#app',
      data: {
      
      
        username: '',
        age: '',
      },
      methods: {
      
      
        fatherFn () {
      
      
          alert('老父亲被点击了')
        },
        sonFn (e) {
      
      
          // e.stopPropagation()
          alert('儿子被点击了')
        }
      }
    })
  </script>

Two, v-bind's enhancement of style control - operation class

In order to make it easier for developers to control styles, Vue extends the syntax of v-bind, which can control class names and style inline styles .

1. Grammar:

<div> :class = "对象/数组">这是一个div</div>

2. Object syntax

When the class is dynamically bound to an object , the key is the class name, and the value is a Boolean value . If the value is true , there is this class, otherwise there is no such class

<div class="box" :class="{ 类名1: 布尔值, 类名2: 布尔值 }"></div>

​ Applicable scenario: a class name, switching back and forth

3. Array syntax

When the class is dynamically bound to an array → all classes in the array will be added to the box, which is essentially a class list

<div class="box" :class="[ 类名1, 类名2, 类名3 ]"></div>

Usage scenario: add or delete classes in batches

4. Tab bar switching navigation highlight case

1. Requirements:

​ When we click on which tab page, which tab page will be highlighted

2. Realize

<style>
  * {
    margin: 0;
    padding: 0;
  }
  ul {
    display: flex;
    border-bottom: 2px solid #e01222;
    padding: 0 10px;
  }
  li {
    width: 100px;
    height: 50px;
    line-height: 50px;
    list-style: none;
    text-align: center;
  }
  li a {
    display: block;
    text-decoration: none;
    font-weight: bold;
    color: #333333;
  }
  li a.active {
    background-color: #e01222;
    color: #fff;
  }

</style>

<div id="app">
  <ul>
    <li v-for="(item,index) in list" :key="item.id" @click="activeIndex = index">
      <a :class="{active: index === activeIndex}" href="#">{
   
   { item.name }}</a>
    </li>
  </ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      activeIndex: 0,
      list: [
        { id: 1, name: 'spring' },
        { id: 2, name: 'SpringBoot' },
        { id: 3, name: 'SpringCloud' }
      ]
    }
  })
</script>

image-20230725145508364

3. Ideas:

1. Based on data, dynamically render tab (v-for)

2. Prepare a subscript to record which tab is highlighted

3. Dynamically switch the class name of the class based on the subscript

Three, v-bind's enhancement of style control - operation style

1. Grammar

<div class="box" :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值 }"></div>

2. Progress bar case

image-20230725150443205

<style>
  .progress {
      
      
    height: 25px;
    width: 400px;
    border-radius: 15px;
    background-color: #272425;
    border: 3px solid #272425;
    box-sizing: border-box;
    margin-bottom: 30px;
  }
  .inner {
      
      
    width: 50%;
    height: 20px;
    border-radius: 10px;
    text-align: right;
    position: relative;
    background-color: #409eff;
    background-size: 20px 20px;
    box-sizing: border-box;
    transition: all 1s;
  }
  .inner span {
      
      
    position: absolute;
    right: -20px;
    bottom: -25px;
  }
</style>

<div id="app">
  <div class="progress">
    <div class="inner" :style="{ width: percent + '%'}">
      <span>{
   
   {percent}}%</span>
    </div>
  </div>
  <button @click="percent = 25">set25%</button>
  <button @click="percent = 50">set50%</button>
  <button @click="percent = 75">set75%</button>
  <button @click="percent = 100">set100%</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  const app = new Vue({
      
      
    el: '#app',
    data: {
      
      
      percent: 0
    }
  })
</script>

Fourth, the use of v-model in other form elements

1. Explanation content:

Common form elements can be associated with v-model binding → quickly get or set the value of the form element

It will automatically choose the correct method to update the element according to the control type

输入框  input:text   ——> value
文本域  textarea	 ——> value
复选框  input:checkbox  ——> checked
单选框  input:radio   ——> checked
下拉菜单 select    ——> value
...

2. Case

image-20230725154228981

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="./css/index.css" />
  <title>记事本</title>
</head>
<style>
  textarea {
      
      
    display: block;
    width: 240px;
    height: 100px;
    margin: 10px 0;
  }
</style>
<div id="app">
  <h3>信息收集</h3>
  姓名:
  <input type="text" v-model="username">
  <br><br>
  是否单身:
  <input type="checkbox" v-model="isSingle">
  <br><br>
  <!--
    前置理解:
      1. name:  给单选框加上 name 属性 可以分组 → 同一组互相会互斥
      2. value: 给单选框加上 value 属性,用于提交给后台的数据
    结合 Vue 使用 → v-model
  -->
  性别:
  <input v-model="gender" type="radio" name="gender" value="1"><input v-model="gender" type="radio" name="gender" value="2"><br><br>
  <!--
    前置理解:
      1. option 需要设置 value 值,提交给后台
      2. select 的 value 值,关联了选中的 option 的 value 值
    结合 Vue 使用 → v-model
  -->
  所在城市:
  <select v-model="cityId">
    <option value="101">合肥</option>
    <option value="102">杭州</option>
    <option value="103">苏州</option>
    <option value="104">南京</option>
  </select>
  <br><br>
  自我描述:
  <textarea v-model="desc"></textarea>
  <button>立即注册</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  const app = new Vue({
      
      
    el: '#app',
    data: {
      
      
      username: '',
      isSingle: false,
      gender: "2",
      cityId: '101',
      desc: ""
    }
  })
</script>

Five, computed calculation properties

1. Concept

Based on existing data , new attributes are calculated . Dependent data changes and is automatically recalculated.

2. Grammar

  1. Declared in the computed configuration item , a computed property corresponds to a function
  2. It is used like a normal attribute using { { computed attribute name }}

3. Pay attention

  1. Computed configuration items and data configuration items are at the same level
  2. Although the computed attribute in computed is written as a function , it is still an attribute
  3. The computed attribute in computed cannot have the same name as the attribute in data
  4. Using computed attributes in computed is the same as using attributes in data
  5. The this inside the computed property in computed still points to the Vue instance

4. Case

For example, we can use computed properties to implement the following business scenario

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<style>
    table {
      
      
        border: 1px solid #000;
        text-align: center;
        width: 240px;
    }
    th,td {
      
      
        border: 1px solid #000;
    }
    h3 {
      
      
        position: relative;
    }
</style>

<div id="app">
    <h3>礼物清单</h3>
    <table>
        <tr>
            <th>名字</th>
            <th>数量</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
            <td>{
   
   { item.name }}</td>
            <td>{
   
   { item.num }}个</td>
        </tr>
    </table>

    <!-- 目标:统计求和,求得礼物总数 -->
    <p>礼物总数:{
   
   { totalCount }} 个</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
    const app = new Vue({
      
      
        el: '#app',
        data: {
      
      
            // 现有的数据
            list: [
                {
      
       id: 1, name: '篮球', num: 1 },
                {
      
       id: 2, name: '玩具', num: 2 },
                {
      
       id: 3, name: '铅笔', num: 5 },
            ]
        },
        computed: {
      
      
            totalCount(){
      
      
                let total =  this.list.reduce((sum,item) => sum + item.num,0)
                return total
            }
        }
    })
</script>
</html>

image-20230725155709314

6. Comparison of computed properties and methods

1. computed property

Function: Encapsulate a section of data processing and obtain a result

grammar:

  1. Write in the computed configuration item
  2. As an attribute, use directly
    • Computed properties are used in js: this.Computed properties
    • Computed properties are used in templates: { {computed property}}

2. methods computed properties

Role: Provide a method for the Vue instance to call to process business logic .

grammar:

  1. Write in the methods configuration item
  2. as a method call
    • Call in js: this. method name ()
    • Call { {method name()}} or @event name="method name" in the template

3. Advantages of Computed Attributes

  1. Caching features (improving performance)

    Computed properties will cache the calculated results, and use the direct read cache again. If the dependencies change, they will be automatically recalculated → and cached again

  2. methods have no caching feature

  3. Compare by code

4. Summary

1.Computed has caching features , but methods have no caching

2. When a result depends on multiple other values, it is recommended to use computed properties

3. When dealing with business logic, it is recommended to use methods, such as event handlers

Seven, the complete writing of the calculated attribute

Since computed properties are also properties and can be accessed, they should also be able to be modified?

  1. The default shorthand for computed properties, which can only be read and accessed, and cannot be "modified"
  2. If you want to "modify" → you need to write the full wording of the computed property

c9d8ed4a2c28faadebff53697991d848

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>改名卡</title>
</head>
<body>
<div id="app">
  姓:<input type="text" v-model="firstName"> +
  名:<input type="text" v-model="lastName"> =
  <span>{
   
   { fullName }}</span><br><br>
  <button @click="changeName">改名卡</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      firstName: '刘',
      lastName: '备'
    },
    computed: {
      fullName: {
        get(){
          return this.firstName + this.lastName
        },
        set(value){
          this.firstName=value.slice(0,1)
          this.lastName=value.slice(1)
        }
      }
    },
    methods: {
        changeName(){
          this.fullName='貂小婵'
        }
    }
  })
</script>
</body>
</html>

Eight, watch listener (monitor)

1. Function:

​Monitor data changes , perform some business logic or asynchronous operations

2. Grammar:

  1. watch is also declared in the configuration item at the same level as data

  2. Simple writing: direct monitoring of simple type data

  3. Complete writing: add additional configuration items

    data: {
          
           
      words: '苹果',
      obj: {
          
          
        words: '苹果'
      }
    },
    
    watch: {
          
          
      // 该方法会在数据变化时,触发执行
      数据属性名 (newValue, oldValue) {
          
          
        一些业务逻辑 或 异步操作。 
      },
      '对象.属性名' (newValue, oldValue) {
          
          
        一些业务逻辑 或 异步操作。 
      }
    }
    

3. watch listener

Complete writing —> add additional configuration items

  1. deep:true deep monitoring of complex types
  2. immdiate: true initialization is executed once immediately
data: {
    
    
  obj: {
    
    
    words: '苹果',
    lang: 'italy'
  },
},

watch: {
    
    // watch 完整写法
  对象: {
    
    
    deep: true, // 深度监视
    immdiate:true,//立即执行handler函数
    handler (newValue) {
    
    
      console.log(newValue)
    }
  }
}

1. Simple writing

watch: {
    
    
  数据属性名 (newValue, oldValue) {
    
    
    一些业务逻辑 或 异步操作。 
  },
  '对象.属性名' (newValue, oldValue) {
    
    
    一些业务逻辑 或 异步操作。 
  }
}

2. Complete writing

watch: {
    
    // watch 完整写法
  数据属性名: {
    
    
    deep: true, // 深度监视(针对复杂类型)
    immediate: true, // 是否立刻执行一次handler
    handler (newValue) {
    
    
      console.log(newValue)
    }
  }
}

Guess you like

Origin blog.csdn.net/qq_54351538/article/details/131938710