This is the 27th day of my participation in the August Genwen Challenge.More challenges in August

In this article we will look at the use of the instance methods $watch, $emit, $forceUpdate, and $nextTick, and what we need to be aware of.

How to use

$watch

Officially, listen for changes in the computed results of reactive properties or functions on component instances. The callback takes new and old values. We can only pass the top-level names of Data, props, or computed Property as strings. For more complex expressions, replace them with a function.

The essence is: we’re listening for a piece of data, and when that data changes, we’re going to do something. Let’s first define an example as follows:

const { createApp, ref, reactive } = Vue
const app = createApp({
    setup() {
        const name = ref('also laugh')
        const obj = reactive({
            name: "Laughing".info: {
                englishName: "slifree"}})return {
            name,
            obj
        }
    },
})
const vm = app.mount("#app")
Copy the code

So we can use it as follows:

Listening for underlying data

vm.$watch('name'.(newV,oldV) = >{
    console.log(newV,oldV)
})
Copy the code

Listen to the object

vm.$watch(
    () = > vm.obj.info.englishName,
    (newV, oldV) = > {
        console.log(newV, oldV)
    }
)
Copy the code

Note that when listening for a property of an object, the first argument of $watch must be passed as a callback function, otherwise, no listening will be triggered.

Listen to the arguments

vm.$watch('obj'.(newV, oldV) = > {
    console.log(newV, oldV)
}, {
    deep: true.immediate: true.flush: 'pre'
})
Copy the code
  • deep: true: Deep listening
  • immediate: true: Triggers a callback immediately with the current value of the expression
  • flush: Controls the timing of the callback. It can be set to'pre','post' 或 'sync'

Stop listening

const unwatch = vm.$watch('name'.(newV,oldV) = >{
    console.log(newV,oldV)
})
unwatch()
Copy the code

$watch returns an unlistener function to stop triggering the callback.

You can also refer back to the Vue3 API article (10) for more information.

$emit

Triggers events on the current instance. Additional parameters are passed to the listener callback. We use emits when we define events in the component.

Suppose we define a component as follows:

app.component('my-component', {
    emits: ['change'].// What to watch out for
    props: ['name'].data() {
        return {
            value: ' '}},template: ` < h1 > < input type = "text" v - model = "value" > < button @ click = "$emit (' change ', value)" > {{name}} < / button > / / need to be aware of local < / h1 > `
})
Copy the code

It is worth noting that the events listed in the emits option are not inherited from the root element of the component and will also be removed from the $attrs property.

emits can be arrays or objects that trigger custom events from components, and emits can be simple arrays or objects that allow event validation to be configured.

$forceUpdate

Force component instances to be re-rendered. Note that it affects only the instance itself and the children that insert slot content, not all children, using the following:

this.$forceUpdate()
Copy the code

We can use this method to force the instance to be rendered again when we have too much data, the render function does not fire, or at some point the render is paused. But this method, we don’t usually use.

$nextTick

Officially, the callback is deferred until after the next DOM update cycle. Use the data immediately after you modify it, and then wait for DOM updates. It is the same as the global method nextTick, except that the this callback is automatically bound to the instance calling it. Use as follows:

methods: {
    // ...
    changeName() {
        // Modify the data
        this.name = 'also laugh'
        // DOM has not been updated
        this.$nextTick(function () {
            // DOM is now updated
            // 'this' is bound to the current instance
            this.doSomethingElse()
        })
    }
}
Copy the code

After the DOM update, we can take a look back at the nextTick usage in Vue3 API (7).

conclusion

  1. The first argument to $watch must be passed as a callback function; otherwise, no listening is triggered.

  2. According to the requirements, we need to send reasonable parameters to $watch.

For more articles, the portal has opened: Look back at the Vue3 catalogue!