Vue watch monitors data changes


Listening to data changes is implemented in Vue through a listener, and you can also understand it as a listener, always listening to a certain data change

Basic usage of watch

This time we are going to add the watch attribute. Let's get familiar with where to add the listener first:

<script>
    export default {
    
    
        name: "app",
        // 数据
        data() {
    
    
            return {
    
    };
        },
        // 方法
        methods:{
    
    },
        // 侦听器
        watch:{
    
    }
    };
    </script>

A simple example:

 <template>
       <p>你点击按钮的次数是: {
    
    {
    
     count }} </p>
       <button @click="add" v-model="count">点击</button>
   </template>

   <script>
   export default {
    
    
       name: "app",
       data(){
    
    
           return {
    
    
               count:0
           }
       },
       methods:{
    
    
           add(){
    
    
               this.count++;
           }
       },
       watch:{
    
    
           // 被侦听的变量count
           count(){
    
    
               console.log('count 发生了变化');
           }
       }
   };
   </script>

The listener is more used in asynchronous operations. The so-called asynchronous operation is the operation with delayed data return. For example, if we want to request the interface of the backend, the interface will return the data to us, and then we will render the data on the page .

From requesting the interface to returning data, it takes a certain amount of time. At this time, we can use the listener to listen to the returned data. When the data is returned, we will trigger the rendering.

Simulate a pseudo-asynchronous operation:

    <template>
        <input type="text" v-model="inputValue">
        <p>从输入框中获取到的数据:{
    
    {
    
     passedInputValue }}</p>
    </template>

    <script>
    export default {
    
    
        name: "app",
        data(){
    
    
            return {
    
    
                inputValue: '',
                passedInputValue: ''
            }
        },
        watch:{
    
    
            inputValue() {
    
    
                // 当inputValue数据发生变化以后,延迟三秒赋值给passedInputValue
                setTimeout(() => {
    
    
                    this.passedInputValue = this.inputValue;
                }, 3000)
            }
        }
    };
    </script>

At this point, you will find that when you enter text in the input box, the data in the p tag does not change immediately, but will be rendered after three seconds

Get the previous value

In some scenarios, we will need the last data, at this time, the listener can give us two values, the old value and the new value

On the basis of the previous case, we only need to add a parameter to get the old value, the code is as follows:

watch:{
    
    
        inputValue(value,oldValue) {
    
    
            // 第一个参数为新值,第二个参数为旧值,不能调换顺序
            console.log(`新值:${
      
      value}`);
            console.log(`旧值:${
      
      oldValue}`);
        }
    }

handler method and immediate attribute

We already know that when the value we listen to has not changed, the listener will not be triggered, and the listener will not be triggered when the page is rendered for the first time.

But now I have a need to trigger the listener when the page is rendered for the first time?
At this point, a method and an attribute are used: immediate

    <template>
        <p>FullName: {
    
    {
    
    fullName}}</p>
        <p>FirstName: <input type="text" v-model="firstName"></p>
    </template>

    <script>
    export default {
    
    
        name: "app",
        data(){
    
    
            return {
    
    
                firstName: 'Su',
                lastName: 'Junyang',
                fullName: ''
            }
        },
        watch:{
    
    
            firstName: {
    
    
                handler(newName, oldName) {
    
    
                    this.fullName = newName + ' ' + this.lastName;
                },
                // 如果设置了false,那么在页面第一次渲染以后不会触发侦听器
                immediate: true
            }
        }
    };
    </script>

deep deep listening

The so-called deep listening is to listen to the value of the internal property of the object.

The listeners we used before can only listen to changes in one variable, (focus on the comments in the code) for example:

data:{
    
    
    return {
    
    
        // 字符串发生变化,可以侦听
        firstName: 'Su',
        room:{
    
    
            name:"大床房",
            // 当房号发生变化的时候,侦听器并不能侦听到。
            // 因为侦听器只侦听到room,不能侦听number或者name
            number: 302
        }
    }
},

At this time, we need deep listening. It is not difficult to implement deep listening in code. We only need to add a deep attribute on the basis of the handler. The code is as follows:

watch:{
    
    
    room:{
    
    
        handler(newRoom,oldRoom){
    
    
            console.log("房间号发生了变化")
        },
        deep: true
    }
}

Example: Using Listeners and Timers to Implement a Pseudo-Fuzzy Search

 <template>
      <div class="search">
        <input type="text" v-model="inputValue" />
        <div class="search-block" v-for="(element, index) in results" :key="index">
          {
    
    {
    
     element }}
        </div>
      </div>
    </template>
     
    <script>
    export default {
    
    
      name: 'app',
      data() {
    
    
        return {
    
    
          results: [],
          mockData: [
            '浙江大学',
            '中国人民大学',
            '清华大学',
            '清华大学附属中学',
            '浙江理工大学',
            '浙江工业大学'
          ],
          inputValue: ''
        };
      },
      watch: {
    
    
        inputValue(value) {
    
    
          if (!!value) {
    
    
            setTimeout(() => {
    
    
              this.results = this.mockData.filter(el => {
    
    
                console.log(value);
     
                return el.indexOf(value) !== -1;
              });
            }, 300);
          }
        }
      }
    };
    </script>

Guess you like

Origin blog.csdn.net/qq_68862343/article/details/131522576