Introduce in detail the concept, usage and some common application scenarios of listening attributes in Vue3

Vue is a popular JavaScript framework for building user interfaces. In Vue, we often need to monitor data changes and perform corresponding operations when the data changes. Vue3 provides a feature called "monitor attribute", which makes data monitoring easier and more efficient. This article will introduce in detail the concept, usage and some common application scenarios of listening attributes in Vue3.

The basic concept of listening properties

Definition of listening properties

In Vue3, we can watchcreate listener properties through functions. watchThe function accepts two parameters: the data to be monitored and a callback function, which will be automatically triggered when the data changes. Here is an example of a listener property:

<template>
  <div>
    <p>{
   
   { message }}</p>
  </div>
</template>

<script>
import { reactive, watch } from 'vue'

export default {
  setup() {
    const state = reactive({
      message: 'Hello, Vue3!'
    })

    watch(() => state.message, (newVal, oldVal) => {
      console.log(`Message changed from "${oldVal}" to "${newVal}"`)
    })

    return {
      message: state.message
    }
  }
}
</script>

In the above code, we use reactivethe function to create a reactive state object state, which contains a property message. We then use watcha function to listen state.messagefor changes and print out the old and new values ​​when they change.

Configuration options for listening properties

In addition to monitoring data changes, we can further control monitoring behavior through configuration options. watchThe third parameter of the function is a configuration object, which is used to specify more options. Here is an example:

<template>
  <div>
    <p>{
   
   { count }}</p>
  </div>
</template>

<script>
import { reactive, watch } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0
    })

    watch(
      () => state.count,
      (newVal, oldVal) => {
        console.log(`Count changed from "${oldVal}" to "${newVal}"`)
      },
      {
        immediate: true,
        deep: true
      }
    )

    return {
      count: state.count
    }
  }
}
</script>

In the above code, we added a configuration object with two options: immediateand deep. immediateThe option is used to specify whether to execute the callback function immediately when the monitoring is started, the default is false; deepthe option is used to specify whether to perform deep monitoring, the default is false. Through configuration options, we can more flexibly control the behavior of monitoring.

Use of listener properties

Listening to basic data types

In Vue3, we can listen for changes in basic data types (such as strings, numbers, booleans, etc.). Here's an example that listens to primitive data types:

<template>
  <div>
    <input v-model="message" />
    <p>{
   
   { message }}</p>
  </div>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  setup() {
    const message = ref('Hello, Vue3!')

    watch(message, (newVal, oldVal) => {
      console.log(`Message changed from "${oldVal}" to "${newVal}"`)
    })

    return {
      message
    }
  }
}
</script>

In the above code, we use refthe function to create a reactive basic data type variable message. We then use watcha function to listen messagefor changes and print out the old and new values ​​when they change.

Listener objects and arrays

In addition to basic data types, we can also monitor changes in objects and arrays. In Vue3, when we monitor objects or arrays, by default we only monitor the changes of the objects or arrays themselves, not the changes of their internal properties. If you need to monitor the changes of objects or arrays in depth, you can deepset the option to true. Here's an example of a listener object and array:

<template>
  <div>
    <input v-model="userInfo.name" />
    <ul>
      <li v-for="task in tasks" :key="task.id">{
   
   { task.name }}</li>
    </ul>
  </div>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  setup() {
    const userInfo = ref({ name: 'John Doe' })
    const tasks = ref([
      { id: 1, name: 'Task 1' },
      { id: 2, name: 'Task 2' },
      { id: 3, name: 'Task 3' }
    ])

    watch(
      userInfo,
      (newVal, oldVal) => {
        console.log('User info changed:', newVal, oldVal)
      },
      { deep: true }
    )

    watch(
      tasks,
      (newVal, oldVal) => {
        console.log('Tasks changed:', newVal, oldVal)
      },
      { deep: true }
    )

    return {
      userInfo,
      tasks
    }
  }
}
</script>

In the above code, we use reffunctions to create a reactive object userInfoand array tasks. Then, we use watchfunctions to listen for their changes, and implement deep monitoring by setting deepoptions to .true

Application Scenarios of Monitoring Attributes

Form Validation and Data Processing

In actual development, we often need to monitor changes in form fields, and perform validation and data processing based on field values. By listening to attributes, we can monitor the changes of form fields in real time and execute corresponding validation logic when they change. Here's an example of listening to a form field:

<template>
  <div>
    <input v-model="username" />
    <p v-if="isUsernameInvalid">Invalid username!</p>
  </div>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  setup() {
    const username = ref('')
    const isUsernameInvalid = ref(false)

    watch(username, (newVal) => {
      // Perform validation logic
      if (newVal.length < 4 || newVal.length > 16) {
        isUsernameInvalid.value = true
      } else {
        isUsernameInvalid.value = false
      }
    })

    return {
      username,
      isUsernameInvalid
    }
  }
}
</script>

In the above code, we use reffunctions to create a reactive string variable usernameand boolean variable isUsernameInvalid. We then use watcha function to listen usernamefor changes and validate against the length of the username. isUsernameInvalidSet to if the length of the username is less than 4 or greater than 16, else trueset to false. In the template, we isUsernameInvaliddisplay the corresponding error message according to the value of .

Asynchronous requests and side effects handling

During the development process, we often need to obtain data through asynchronous requests and process the data after it returns. By monitoring properties, we can monitor data changes in real time and perform corresponding side-effect processing when data changes. Here's an example of handling an asynchronous request:

<template>
  <div>
    <button @click="loadData">Load Data</button>
    <p v-for="item in data" :key="item.id">{
   
   { item.name }}</p>
  </div>
</template>

<script>
import { ref, watch } from 'vue'

export default {
  setup() {
    const data = ref([])

    const loadData = async () => {
      const response = await fetch('https://api.example.com/data')
      const result = await response.json()
      data.value= result
    }

    watch(data, () => {
      // Perform side effect on data change
      console.log('Data changed:', data.value)
    })

    return {
      data,
      loadData
    }
  }
}
</script>

In the above code, we use refthe function to create a responsive array datato store the data returned by the asynchronous request. Then, we define a loadDatafunction that triggers an asynchronous request and assigns the returned data to data. With watchfunctions, we listen datafor changes and perform side effects when data changes, such as printing data to the console.

Summarize

Vue3's monitoring property is a powerful and flexible feature that can help us monitor data changes in real time and perform corresponding operations when they change. Whether dealing with form validation, data processing, or asynchronous requests, listener properties provide good support.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131788820