In Vue, computed, watch, and methods are three ways to process responsive data. Their main differences are calculation methods, response methods and usage scenarios.
computed
computed is a computed property that automatically calculates a new value based on the responsive data it depends on, and the computed result will be cached and will only be recalculated when the dependency data changes. That is to say, when the dependency data does not change, multiple accesses to the computed property will immediately return the previously cached calculation result, without executing the computed function again. And computed is essentially a read-only property, which does not modify any responsive data, but only calculates a new value based on the data it depends on.
The advantage of using computed is that it can encapsulate complex computational logic in one property and compute only when needed, and return only the last computational cache value when the dependency data has not changed, thus improving code readability and performance.
computed: { get: function () { return + ' ' + ;// There must be a return }, }
watch
watch is an observer pattern. It will execute a callback function when the observed responsive data changes. In the callback, two parameters newVal and oldVal will be passed. The watch can listen to one or more responsive data and can perform asynchronous operations, such as sending network requests or operating local storage, etc.
The advantage of using watch is that it can monitor changes in data and perform corresponding operations. For example, we can use watch to listen for changes in an input box and send network requests based on the value of the input box:
watch: { inputValue(newValue, oldValue) { // Send network request according to the value of the input box fetch('/api?query=' + newValue) .then(response => ()) .then(data => = data); } }
In this example, when the inputValue changes, the watch will automatically execute the callback function and send a network request based on the value of the input box.
methods
methods is a normal JavaScript method that can receive parameters and execute arbitrary JavaScript code. methods will not automatically respond to data changes and require manual calls to update the view. The methods method is each called, and the methods are executed, and it is not responsive.
The advantage of using methods is that it can execute arbitrary JavaScript code and can pass in different parameters according to specific needs. For example, we can use methods to handle user click events:
methods: { handleClick(event) { // Handle user click events ('User clicked on', ); } }
In this example, when the user clicks on an element, the handleClick method is called and the event object is passed in as a parameter.
The differences between the three
methods, watch and computed are all function-based, but each is different;
1、methods
There is no cache, execute once and run once, execute n times, run n times
2、computed
Usage scenario: When some data on the page depends on other data for changes, you can use the calculation attributes
Computed attributes are processed based on data in data. The data data changes, and it also changes.
When the data in data has not changed, we call the computed function n times and will only cache (execute once)
Each computed attribute contains two set and get attributes
<div>{{get}} </div> //When calling, just write the function name directly
computed: { get: function () { //It is not suitable to write get() here, syntax stipulates return + ' ' + ;// There must be a return }, }
3、watch
Use scenario: When data changes, perform asynchronous or overhead operations, and the changes in state can be modified at any time.
watch: Similar to the listening mechanism + event mechanism.
In most cases, we will use computed, but if we want to perform asynchronous operations or have a relatively large overhead while data changes, then watch is the best choice. watch is an object, the key is the expression that needs to be observed, and the value is the corresponding callback function. The value can also be a method name, or an object containing options.
// This is directly used to bind with v-model, and there is no need to add a change event
<input type="text" v-model="name" /> {{tip}} data() { return { name: "", tip: "" }; }, methods: { checkName(value) { var arg = this; setTimeout(() => { if (value == "aa") { = "The username already exists"; } else { = "Username is available"; } }, 1000); } }, watch: {// Perform asynchronous or overhead operations when data changes name(value) { (value); = "Verifying..."; } }
Advanced usage of watch
The above watch method will trigger the listening event when the value is changed, but we want to trigger the listening event when we first enter the page, so we need to use the handler() method.
1. handler(): When the page just enters, the watch event is automatically bound and does not need to be triggered.
watch: {// This event will be automatically triggered when the page is loaded name:{ handler(new){ (value); = "Verifying..."; } } }
2. immediate attribute: boolean value
immediate: true: listen for data changes when loaded for the first time
immediate: false: listen only if there is a change
watch: {// This event will be automatically triggered when the page is loaded name:{ handler(new){ (value); = "Verifying..."; }, immediate: true } }
3. deep:true; When it is necessary to listen for changes in an object, ordinary watch methods cannot listen for changes in the internal properties of the object. At this time, deep attributes are required to listen for deep to the object.
data() { return { name: { 'fristname': 'a', 'lastname': 'a' }, nameCount:0 } }, watch: { name: { handler(newVal) { ++ }, deep: true } }
Set deep:true to listen to the change of name. At this time, this listener will be added to all attributes of name. When there are many attributes of the object, handler will be executed for each attribute value change.
If you only need to listen for one attribute value in the object, you can listen for the object attributes in the form of a string:
watch: { '': { handler(newVal) { ++ }, deep: true } }
This is the article about the difference between computed attributes and watch and methods in Vue. For more related Vue computed attributes and watch and methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!