When writing Dojay-MD, there is a method to listen for changes in the input content. The code is as follows:
methods: {
/ /... Omit code...
editor.on('change', () = > {const mdValue = editor.getValue()
})
/ /... Omit code...
}
Copy the code
After change, mdValue was processed. At that time, the idea was to write a method in the methods method to deal with it. As follows:
methods: { // ... Omit code... editor.on('change', () => {const mdValue = editor.getValue() this.valuechange (mdValue)}), valueChange(value) {// do something wrong} //... Omit code... }Copy the code
It doesn’t feel right, why don’t I write in watch or computed?? — Because I’m scum.
compunted: {
mdValue() {// do something}}, // or watch: {mdValue() {// do something}}Copy the code
The question is, methods, Watch and computed can all do this, but what is the difference between them?
Methods, Watch, computed difference
- Watch and computed are based on the dependency tracking mechanism of Vue. When a certain data changes, all related data that depend on this data changes automatically.
- Methods need to be called manually.
Watch and computed
- Computed caches data; Watch does not
- Watch supports asynchronous operations, but computed does not. For asynchronous operations when data changes or for high overhead, watch is the best choice.
- If the data of watch does not exist in data, it cannot be watched. The existence of computed data in data is an error.
- Things watch is good at: one data change affects multiple data; Computed is good at dealing with data: multiple data affect one
todo:
- How do Watch and Computed work (source)
- Computed Data Caching (source code)