The watch monitor 381 vue: persistence data, basic data types listening, listening objects, attributes, and calculate the difference between the watch

1, persistent data (stored locally)

1. 可以在数组的`增删改`, 都要保存一下, 比较繁琐
2. 监听数组的变化, 数组一旦发生变化, 在监听里面 保存一下(代码写一遍就可以了)

vue 提供了一个监听器.

TodoMVC data persistence

Requirements: The data todoMVC is saved to 本地存储the (local persistence)

  1. When the stored data?

    Because the CRUD functions will modify the list of data, so long as the list data is changed, it is necessary to save local storage;
    Method One: CRUD methods to save the data in the call, respectively, (not recommended too tedious)
    Method two: find a way change the monitor list data, as long as the list data has changed, then call the method to save data

Vue data can be used to change the watch list of listening

  1. Stored value

    Need to listen and monitor an array of objects as depth monitor
    the stored value, remember the object into a string (stored fast, space-saving)

   // 监听
   watch: {
      // 监听list
      todoList: {
         deep: true,
         handler(newVal) {
            // console.log('发生变化了', newVal)
            // 保存起来
            localStorage.setItem('todoList', JSON.stringify(newVal))
         }
      }
   },
  1. The value may be the initial value in data

    Remember to give a default value empty array []

    const todoList =  JSON.parse(localStorage.getItem('todoList')) || [],

2. Description

Vue by the watch configuration item, to monitor changes in the data instance vue


3, the basic use

watch: {
    // 监听name属性的数据变化
    // 作用 : 只要name的值发生变化,这个方法就会被调用
    // 第一个参数 : 新值
    // 第二个参数 : 旧值,之前的前
    name(newVal,oldVal){
            console.log('新 :',newVal);
            console.log('旧 :',oldVal);
    }
}

4, the basic use case

Requirements: monitor the user name text box the number of characters (3-6), and display format validation

<input type="text" v-model="name" />
<span v-show="isShow">用户名的字符 在 6-12之间</span> if
(/^[0-9a-zA-Z]{3,6}$/.test(newVal)) { 验证 }

5, listening objects (also part of an array of objects)

// data :
 data: {
   obj: {
   name: 'zs'
   }
},
// 组件
<input type="text" v-model="obj.name" />
// 监听

6, start listening for object properties

// 从对象的角度来监听的
 因为对象和数组都是引用类型,引用类型变量存的是地址,地址没有变,所以不会触发watch
obj:{
    // 深度监听 属性的变化
    deep:true,
    // 立即处理 进入页面就触发
    immediate: true,  
    // 数据发生变化就会调用这个函数  
    handler( newVal ) {
      console.log( newVal.name );
     }
  },
 // 从属性的角度来监听
 'obj.name' ( newVal ) {
      console.log('监听对象的属性',newVal);
 }

7, and calculates the difference between the properties of the watch

computed 和 watch的区别
computed :  计算属性
    - 1.根据已知值 ,得到一个新值 
        - 2. 新值随着已知值(相关的数据)变化而变化 
        1. 计算属性 ==> (得到的是)新值
        2. 计算属性(num)  ==> 是别人影响了我

watch : 监听器
1. 监听 ==> (监听)已知值
2. 监听数据 (num2) => 是我影响到了别人

8, naming rules: Alphanumeric _ $

let xxx = 'sex'

let obj = {
  'mg-name': 'zs',
  age: 20,
  // sex : '男'
  [xxx] : '男'
}

Basic use 05- listener - my .html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div id="app">
        <h1>{{ num }}</h1>
        <button @click="fn">按钮</button>
    </div>

    <script src="./vue.js"></script>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                num: 100,
                msg: {}
            },
            methods: {
                fn() {
                    for (let i = 0; i < 5; i++) {
                        this.num++
                    }
                }
            },
            watch: {
                num(newVal, oldVal) {
                    console.log(`新值是:${newVal},旧值是:${oldVal}`); // 新值是:105,旧值是:100
                }
            }
        })
    </script>

</body>

</html>
<script>
</script>

06- listener listening complex type .html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>

<body>
    <div id="app">
        <input type="text" v-model="obj.name" />
    </div>
    <script src="./vue.js"></script>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                obj: {
                    name: 'zs'
                }
            },
            // 监听
            watch: {
                // 监听 obj ,如果监听成功 newVal 就是obj的最新值 newVal 也是对象
                // 因为obj是复杂类型 引用类型,直接这么写,监听的是对象的地址 【所以只有地址发送改变时,才会监听到。】
                // obj(newVal) {
                //   console.log(newVal.name)
                // }

                // 方式1 : 监听对象+ 深度监听 【注意语法】
                obj: {
                    deep: true, // 深度监听
                    immediate: true, // 立即监听
                    // 处理
                    handler(newVal) {
                        console.log(newVal.name)
                    }
                },

                // 方式2: 简单粗暴的直接监听对象里的属性(name)
                'obj.name' (newVal) {
                    console.log(newVal)
                }
            }
        })
    </script>
</body>

</html>

Small Case 08- listener .html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!-- 
        需求 : 监听文本框内容的字符串长度 (3-6) , 如果超过范围,提示格式不正确
    -->
    <div id="app">
      <input type="text" v-model="msg" />
      <span v-show="isShow">格式不正确</span>
    </div>
    <script src="./vue.js"></script>
    <script>
      const vm = new Vue({
        el: '#app',
        data: {
          msg: '',
          isShow: false
        },
        watch: {
          msg(newVal) {
            if (newVal.length >= 3 && newVal.length <= 6) {
              console.log('格式正确')
              this.isShow = false
            } else {
              console.log('格式不正确')
              this.isShow = true
            }
          }
        }
      })
    </script>
  </body>
</html>

09- calculating the difference between the listener and the attribute .html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>

<body>
    <!-- 
    计算属性 computed       
    监听器 watch

    计算属性 : 
      - 根据已知值, 得到一个新值
      - 新值随着`相关的数据`发生变化而变化
      - 是一个新值, 不是data里的值
      区别 :
        - 别人改变, 影响到了我
    
    监听器
      - 监听数据的变化  
      - 监听的不是一个新值(可以是data里的值)
      
      区别 :
      - 我改变了, 去影响别人 【被监听的数据改变了,会触发一些操作。】 【当被监听的数据改变了,就......】
   -->

    <div id="app"></div>
    <script src="./vue.js"></script>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                num1: 100,
                num2: 200
            },
            computed: {
                totalNum() {
                    return this.num1 + 20
                }
            },
            watch: {
                num2(newVal) {
                    // console.log(newVal)
                    if (newVal <= 205) {
                        console.log('我想干第一件事')
                    } else {
                        console.log('我想干第二件事')
                    }
                }
            }
        })
    </script>
</body>

</html>

Guess you like

Origin www.cnblogs.com/jianjie/p/12508425.html