[Vue2+3 Getting Started to Practical Combat] (6) Vue Basics Watch Listener (Monitor) Detailed Example

Insert image description here

1. Today’s learning goals

1.watch listener

  1. Basic writing method
  2. Complete writing method

2. watch listener (monitor)

1. Function:

Monitor data changes and 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 method: Direct monitoring of simple type data

  3. Complete writing: Add additional configuration items

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

3. Listener code preparation

 <style>
      * {
      
      
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-size: 18px;
      }
      #app {
      
      
        padding: 10px 20px;
      }
      .query {
      
      
        margin: 10px 0;
      }
      .box {
      
      
        display: flex;
      }
      textarea {
      
      
        width: 300px;
        height: 160px;
        font-size: 18px;
        border: 1px solid #dedede;
        outline: none;
        resize: none;
        padding: 10px;
      }
      textarea:hover {
      
      
        border: 1px solid #1589f5;
      }
      .transbox {
      
      
        width: 300px;
        height: 160px;
        background-color: #f0f0f0;
        padding: 10px;
        border: none;
      }
      .tip-box {
      
      
        width: 300px;
        height: 25px;
        line-height: 25px;
        display: flex;
      }
      .tip-box span {
      
      
        flex: 1;
        text-align: center;
      }
      .query span {
      
      
        font-size: 18px;
      }

      .input-wrap {
      
      
        position: relative;
      }
      .input-wrap span {
      
      
        position: absolute;
        right: 15px;
        bottom: 15px;
        font-size: 12px;
      }
      .input-wrap i {
      
      
        font-size: 20px;
        font-style: normal;
      }
    </style>

 <div id="app">
      <!-- 条件选择框 -->
      <div class="query">
        <span>翻译成的语言:</span>
        <select>
          <option value="italy">意大利</option>
          <option value="english">英语</option>
          <option value="german">德语</option>
        </select>
      </div>

      <!-- 翻译框 -->
      <div class="box">
        <div class="input-wrap">
          <textarea v-model="words"></textarea>
          <span><i>⌨️</i>文档翻译</span>
        </div>
        <div class="output-wrap">
          <div class="transbox">mela</div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      // 接口地址:https://applet-base-api-t.itheima.net/api/translate
      // 请求方式:get
      // 请求参数:
      // (1)words:需要被翻译的文本(必传)
      // (2)lang: 需要被翻译成的语言(可选)默认值-意大利
      // -----------------------------------------------
      
      const app = new Vue({
      
      
        el: '#app',
        data: {
      
      
          words: ''
        },
        // 具体讲解:(1) watch语法 (2) 具体业务实现
      })
    </script>

3. Translation Case-Code Implementation

  <script>
      // 接口地址:https://applet-base-api-t.itheima.net/api/translate
      // 请求方式:get
      // 请求参数:
      // (1)words:需要被翻译的文本(必传)
      // (2)lang: 需要被翻译成的语言(可选)默认值-意大利
      // -----------------------------------------------
      
      const app = new Vue({
    
    
        el: '#app',
        data: {
    
    
           //words: ''
           obj: {
    
    
            words: ''
          },
          result: '', // 翻译结果
          // timer: null // 延时器id
        },
        // 具体讲解:(1) watch语法 (2) 具体业务实现
        watch: {
    
    
          // 该方法会在数据变化时调用执行
          // newValue新值, oldValue老值(一般不用)
          // words (newValue) {
    
    
          //   console.log('变化了', newValue)
          // }

          'obj.words' (newValue) {
    
    
            // console.log('变化了', newValue)
            // 防抖: 延迟执行 → 干啥事先等一等,延迟一会,一段时间内没有再次触发,才执行
            clearTimeout(this.timer)
            this.timer = setTimeout(async () => {
    
    
              const res = await axios({
    
    
                url: 'https://applet-base-api-t.itheima.net/api/translate',
                params: {
    
    
                  words: newValue
                }
              })
              this.result = res.data.data
              console.log(res.data.data)
            }, 300)
          }
        }
      })
    </script>

4. watch listener

1. Grammar

Complete writing method—>Add additional configuration items

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

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

2.Demand

Insert image description here

  • When typing in the text box, the translation content on the right side changes from time to time.
  • When the language in the drop-down box changes, the translated content on the right still needs to change from time to time.
  • If there is a default value in the text box, it must be translated immediately

3. Code implementation

 <script> 
      const app = new Vue({
    
    
        el: '#app',
        data: {
    
    
          obj: {
    
    
            words: '小黑',
            lang: 'italy'
          },
          result: '', // 翻译结果
        },
        watch: {
    
    
          obj: {
    
    
            deep: true, // 深度监视
            immediate: true, // 立刻执行,一进入页面handler就立刻执行一次
            handler (newValue) {
    
    
              clearTimeout(this.timer)
              this.timer = setTimeout(async () => {
    
    
                const res = await axios({
    
    
                  url: 'https://applet-base-api-t.itheima.net/api/translate',
                  params: newValue
                })
                this.result = res.data.data
                console.log(res.data.data)
              }, 300)
            }
          } 
        }
      })
    </script>

4. Summary

How many ways are there to write watch listeners?

1. Simple writing

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

2. Complete writing method

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

5. Comprehensive cases

Shopping cart case

Insert image description here

Statement of needs:

  1. Rendering function
  2. Delete function
  3. Number of modifications
  4. Select all and invert selection
  5. Count the total price and total quantity selected
  6. persist to local

Implementation ideas:

1. Basic rendering: v-for traversal, :class dynamic binding style

2. Delete function: v-on binding event to get the id of the current row

3. Modify the number: v-on binding event, get the ID of the current row, filter out the corresponding items and then increase or decrease

4. Select all and reverse the selection

  1. All small check boxes must be selected before the Select All button is selected → every
  2. If the Select All button is selected, all small check boxes are selected
  3. If you select all and cancel, all small check boxes will be unchecked.

Declare the calculated attribute and determine the value of each checked attribute in the array to see if all of them need to be selected.

5. Count the total price and total quantity selected: Calculate the total price and total quantity selected by calculating attributes

6. Persist to local: Update the local storage watch whenever the data changes.

Guess you like

Origin blog.csdn.net/shenchengyv/article/details/135216678