Detailed explanation of watch in vue

1. Official explanation

An object, the key is the expression to be observed , and the value is the corresponding callback function. Value can also be a method name, or an object containing options. The Vue instance will call $watch() when it is instantiated, traversing each property of the watch object.

simply put:

watch:  It is used to monitor whether the data in data has been modified, and once modified, some other operations can be performed [also a method]

Two, usage

<body>
<div id="app">
    <input type="text" v-model="num">
</div>
<script src="vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            num: ''
        },
        watch: {
            num(newVal, oldVal) {
            // 监听 num 属性的数据变化
    		// 作用 : 只要 num 的值发生变化,这个方法就会被调用 
            //只要没有发生变化,就没有办法进行其他的操作
    		//newData是更新后的数据
            //oldData是旧数据
                console.log('oldVal:',oldVal)
                console.log('newVal:',newVal)
            }
        }
    })
</script>
</body>

3. The difference between watch and computed properties


The difference between computed properties and listened properties

  1. The get of the calculated property must have a return, and the return of the listening property is optional
  2. Computed supports caching, and will only recalculate when dependent data changes; while watch does not support caching, and data changes will directly trigger corresponding operations
  3. Computed properties can customize the name, while listening properties can only monitor the same name as the one in data
  4. Computed properties are suitable for complex operations, while listening properties are suitable for some consumable functions, such as Ajax
  5. Computed does not support asynchronous, and it is invalid when there are asynchronous operations in computed, and cannot monitor data changes, while watch supports asynchronous
  6. Computed attribute values ​​will be cached by default. Computed attributes are cached based on their responsive dependencies, that is, calculated values ​​based on data declared in data or passed by parent components in props; while watch monitoring functions receive two parameters, the first parameter is the latest value, and the second parameter is the value before input
  7. If an attribute is calculated from other attributes, this attribute depends on other attributes, many-to-one or one-to-one, generally use computed; and when an attribute changes, you need to perform the corresponding operation, one-to-many, generally use computed watch

4. Advanced usage of watch

1. immediate (triggered immediately after entering the page)

For example, when the parent component dynamically passes values ​​to the child component, the child component props also needs to execute the function when it obtains the default value from the parent component for the first time. At this time, it is necessary to set the immediate property to true and use it in conjunction with the handler method.

When the immediate property is set to true, no matter whether the value changes, it will be monitored at all times;

When the immediate property is set to false, the normal usage will only listen when the value changes.
 

2. deep (deep monitoring)
When using watch to monitor, we may find that it can monitor a certain data [single data, array], but when monitoring the object, it is obvious that the data has been modified, but there is no monitoring prompt. why?

At this time, we need to enable in-depth monitoring, because when we do not enable in-depth monitoring, the watch will only monitor the first layer, and the data of the object has been modified, but the first address of the object has not been modified, so the watch determines that no data has occurred changes, so you can't monitor

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../../public/js/vue.min.js"></script>
</head>
<body>
<div id="app">
    <h1>{
   
   {text}}</h1>
    <button @click="setHandel">监听</button>
    <h1>{
   
   {array}}</h1>
    <button @click="setArray">更改数组的值</button>
</div>
</body>
</html>
<script>
    new Vue({
        el: '#app',
        data: {
            text:{
                name:'我的一',
                age:21
            },
            array: [1,2,3,4,5]
        },
        methods:{
            setHandel(){
                this.text.name = '我是新的一'
            },
            setArray(){
                /**
                 * 当我们想要更改数组中的值的时候,
                 * this.array[0] = '我是新一',是没有办法修改的
                 * 因为vue的数据双向绑定中,调用的是set和get函数,
                 * 但是在数组里面没有这二个函数
                 * 所以我们只能使用vue封装的$set和变异方法(也就是push啊。。。)
                 */
                this.$set(this.array,0,'我是新一')
            }
        },
        watch: {
            //watch监听器,只能监听第一次,
            //也就是在监听对象的时候,虽然对象中的属性值发生了改变
            //但对象的首地址没有改变,所以监听器认为没有改变数据
            //当想要监听对象的时候,想要开启深度监听
            //deep:true
            text: {
                handler:function () {
                    alert('监听到了')
                },
                deep:true
            }
        }
    })
</script>

 

<body>
<div id="app">
    <input type="button" value="更改名字" @click="change">
</div>
<script src="vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            food: {
                id: 1,
                name: '冰激凌'
            }
        },
        methods: {
            change() {
                this.food.name = '棒棒糖'
            }
        },
        watch: {
        	// 第一种方式:监听整个对象,每个属性值的变化都会执行handler
        	// 注意:属性值发生变化后,handler执行后获取的 newVal 值和 oldVal 值是一样的
            food: {
                // 每个属性值发生变化就会调用这个函数
                handler(newVal, oldVal) {
                    console.log('oldVal:', oldVal)
                    console.log('newVal:', newVal)
                },
                // 立即处理 进入页面就触发
                immediate: true,
                // 深度监听 属性的变化
                deep: true
            },
            // 第二种方式:监听对象的某个属性,被监听的属性值发生变化就会执行函数
            // 函数执行后,获取的 newVal 值和 oldVal 值不一样
            'food.name'(newVal, oldVal) {
                console.log('oldVal:', oldVal)   // 冰激凌
                console.log('newVal:', newVal)   // 棒棒糖
            }
        }
    })
</script>
</body>

Reference: Detailed explanation of the usage of watch (listener) in Vue (easy to understand, simple and clear  ) watch

Watch of Vue 

Guess you like

Origin blog.csdn.net/coinisi_li/article/details/127227327