Home > Web Front-end > Vue.js > body text

What is the watchEffect feature in Vue3

WBOY
Release: 2023-05-20 11:58:22
forward
1477 people have browsed it

    watchEffect is a new feature provided in Vue3, which is used to monitor changes in responsive data and execute the specified callback function when the data changes.

    Different from watch in Vue2, watchEffect does not need to specify the data to be monitored, but will automatically track the reactive data used in the function and use it in these The callback function is re-executed when the data changes. This automatic tracking feature can simplify code and improve application performance.

    The following is an example of using watchEffect:

    import { watchEffect, reactive } from 'vue'
    const state = reactive({
      count: 0
    })
    watchEffect(() => {
      console.log(state.count)
    })
    Copy after login

    In the above code, we use the reactive function to create a reactive objectstate, and used watchEffect to monitor changes in the state.count property. When state.count changes, the callback function will be re-executed.

    It should be noted that watchEffect returns a listener function that does not need to be stopped. If you need to stop listening, you can call this listener function to stop listening.

    In addition to monitoring changes in responsive data, watchEffect also supports accessing the context of the component in the callback function, such as this keywords and calculated properties of the component.

    Here is an example of using watchEffect to access component computed properties:

    import { watchEffect, computed } from 'vue'
    export default {
      computed: {
        doubleCount () {
          return this.count * 2
        }
      },
      mounted () {
        watchEffect(() => {
          console.log(this.doubleCount)
        })
      }
    }
    Copy after login

    In the above code, we create a using the computed function Calculate the property doubleCount, and use watchEffect in the mounted hook function to listen for changes in doubleCount. When doubleCount changes, the callback function will be re-executed.

    The above is the detailed content of What is the watchEffect feature in Vue3. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template