How to use Watch and computed of Vue3
This article introduces the relevant knowledge of "how to use Watch and computed of Vue3". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Computed and watch
Computed
Use the getter function and return an immutable responsive ref object for the value returned from getter.
{{count}}
Import {ref, computed} from 'vue'
Export default {
Setup () {
Const count = ref (1)
Const plusOne = computed (() = > count.value + 1)
Console.log (plusOne.value) / / 2
PlusOne.value++ / / error
Return {
Count
PlusOne
}
}
}
Alternatively, it can use objects with get and set functions to create writable ref objects.
{{count}}
Import {ref, computed} from 'vue'
Export default {
Setup () {
Const count = ref (1)
Const plusOne = computed ({
Get: () = > count.value + 1
Set: val = > {
Count.value = val-1
}
})
Return {
Count
PlusOne
}
}
}
WatchEffect
Run a function immediately when its dependencies are tracked responsively and rerun it when the dependencies are changed.
Const count = ref (0)
WatchEffect (() = > console.log (count.value))
/ /-> logs 0
SetTimeout () = > {
Count.value++
/ /-> logs 1
}, 100)
# # watch
Watch API is completely equivalent to optional API this.$watch (and the corresponding watch option). Watch needs to listen for specific data sources and have side effects in separate callback functions. By default, it is also lazy-that is, the callback is called only when the listening source changes.
Compared with watchEffect, watch allows us to:
Lazily execute side effects
State more specifically that the listener should be triggered to rerun
Accesses the previous and current values of the listening state.
# listening on a single source
The listener data source can be a getter function that returns a value, or it can be ref:
/ / listen on a getter
Const state = reactive ({count: 0})
Watch (
() = > state.count
(count, prevCount) = > {
/ *. /
}
)
/ / listen to a ref directly
Const count = ref (0)
Watch (count, (count, prevCount) = > {
/ *. /
})
This is the end of the content of "how to use Watch and computed in Vue3". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!