computed
computed looks like a method, but it is actually a computed property, which dynamically displays new computation results based on the data you rely on. The calculation result will be cached. The calculated value will be cached after the getter is executed. Only after the property value it depends on changes, the corresponding getter will be called again the next time it obtains the calculated value.
1) Here is a relatively classic and simple case
<template> <div class="hello"> {{fullName}} </div> </template> <script> export default { data() { return { firstName: 'fly', lastName: "Spin" } }, props: { msg: String }, computed: { fullName() { return + ' ' + } } } </script>
Notice
In Vue's template({{}})
It is very convenient to write some simple js expressions, and it is calculated directly as above.{{ + ' ' + }}
, because putting too much declarative logic into the template will make the template itself too heavy, especially when using a large number of complex logical expressions to process data in the page, it will have a great impact on the maintainability of the page. The original design intention of computered is also used to solve such problems.
Application scenarios
Suitable for recalculating time-consuming and no duplicate data calculations. All getters and setters' this context is automatically bound to Vue instances. If one data depends on other data, then design this data as compute
watch
Watcher is more like a data data listening callback. When the data of the dependent data changes, the callback will be executed, and newVal and oldVal will be passed in the method. You can provide an invalid input value and provide intermediate value special scenarios. The Vue instance will call $watch() when instantiated, traversing every property of the watch object. If you need to do something when a certain data changes, use watch.
<template> <div class="hello"> {{fullName}} <button @click="setNameFun">click</button> </div> </template> <script> export default { data() { return { firstName: 'fly', lastName: "Spin" } }, props: { msg: String }, methods: { setNameFun() { = "big"; = "Bear" } }, computed: { fullName() { return + ' ' + } }, watch: { firstName(newval,oldval) { (newval) (oldval) } } } </script>
Summarize
- 1. If one data depends on other data, then design this data as compute
- 2. If you need to do something when a certain data changes, use watch to observe the data changes.
This is the end of this article about the details of the difference between computered and watch in Vue. For more related contents of Vue computered and watch, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!