In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "listeners in vue, what is the difference between cache and computed". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the difference between listeners, caching and computed in vue".
1. Calculation attribute (computed) 1. Vue computed description
When some data needs to change according to other data, it needs to be processed before it can be displayed. Although vue provides a way to bind data expressions, it is originally designed for simple operations. Putting too much logic in the template will make the template overweight and difficult to maintain, may be stretched for some complex and special calculations, and the calculated attributes written in the template are not conducive to project maintenance.
The main roles of computed are:
Separation logic (template and data separation)
Cache value
Bidirectional binding (getter,setter)
2. Grammar format
Format
Computed: {[key: string]: Function | {get: Function, set: Function}}
Parameter description:
Key: string type
Value: it can be a method. If it is a method, it is a get operation by default, or it can be an object. Set the get property or the set property.
3. Basic usage
Description
All kinds of complex logic can be completed in a calculation attribute, including operations, function calls, etc., and finally return a result.
The calculation property can also rely on the data of multiple Vue instances. whenever any of the data changes, the calculation property will be re-executed and the view will be updated, which is suitable for time-consuming data calculation.
Sample code
Let app = new Vue ({el:'# app', data: {id:1, originalPrice:1200, discountPrice:200,}, / / Compute attribute computed: {/ / change the date to a string in a common specification format. CurrentPrice: function () {return "current price:" + (this.originalPrice-this.discountPrice);}); 4. Setter and getter
Description
Each evaluation property contains a getter and a setter. The above example is the default usage of the calculation property, but uses getter to read
If necessary, you can also provide a setter function that triggers the setter function when modifying the value of a calculation property is like modifying an ordinary data
Sample code
Let app = new Vue ({el:'# app', data: {id: 1, originalPrice: 1200, discountPrice: 200,}, / / calculate the attribute computed: {cache:false, / / change the date to a string in a common specification format. CurrentPrice: {get: function () {return "current Price:" + (this.originalPrice-this.discountPrice) }, / / Note that parameters must be passed, otherwise there is no meaning set: function (value) {/ / perform the following custom action this.discountPrice = value}})
Be careful
In most cases, we only use the default getter method to read a calculation property, and setter is rarely used in business, so when declaring a calculation property, we can directly use the default writing method.
5. Caching
Description
Computed attributes are cached based on their dependencies, and will be re-evaluated only when the relevant dependencies change, usually responsive dependencies
What is a responsive dependency? Vue cannot detect the addition or removal of object properties. Because Vue performs the getter/setter conversion process on the property when initializing the instance, the property must exist on the data object for Vue to convert it so that it can be responsive
Sample code
Var vm = new Vue ({data: {/ / declares that message is a null string message:''},}) / / responsive vm.message = 'hellograms' Vm.v= "unresponsive value" methods computed with cached new Vue ({el:'# app', methods: {getMethodsDate: function () {console.log (new Date (). ToLocaleTimeString ())} / / return the calculation property set in the computed option-- computedDate getComputedDate: function () {console.log ("cache-- >" + this.computedDate)}} Computed: {computedDate: function () {return new Date () .toLocaleTimeString ()}}) 6, the difference from methods
Computed will be recalculated only if it meets the two conditions that the dependent data exists and the dependent data changes. And the data under methods will be calculated every time.
The way it is called is different: members defined by computed are accessed like properties, while members defined by methods must be called as functions.
Computed is cached and is recalculated only when its referenced responsive properties change, and functions in methods are executed each time they are called.
5. Listener (watch) 1. Description
Official: this is most useful when you need to perform asynchronous or expensive operations when the data changes. The watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform the operation, and sets the intermediate state before we get the final result.
Watch has the same syntax as the methods we introduced earlier, but with one key difference. Although the value of a nested property is indeed a function, the name of the key must correspond to the name in the data property
2. Syntax format watch: {[key: string]: string | Function | Object}] 3, syntax description
Key: must be an attribute defined in the Vue object data
Value: the value can be a string, the string is the name of the method, the value can be a function, or the value can be an object that contains callback functions with other options, such as whether to traverse depth.
4. Basic use
Sample code
Let vm = new Vue ({data: {test: "111", user: {name:" Code Emperor ", address: {city:" Greater Wuhan "} Methods: {fun: function (val) {alert (val)}}, watch: {/ / method name corresponds to the function name in methods / / test: 'fun', / / function mode test: function (v1) V2) {alert ("new value" + v1 + "= old value:" + v2)}, / * what is depth such as data: {test: "111", user: {name:" Code Emperor ", address {city:' Great Wuhan'} * user attribute corresponding value is deep Push once * if the user property we are listening to is not available when the user.name property changes, so we need to use deep snooping here * / user: {handler: function (val) {alert (val.name)} / / whether deep monitoring defaults to false / / if it is not set to true, when we manually set vm.user.name = "Emperor", deep: true} cannot be monitored. / * or you can use the following ways to monitor * Note that the key value must be a string So enclose * * / "user.address.city" in quotation marks: function (val) {alert (val)}) Vm.test = '333 emperor; vm.user.name = "emperor" Vm.user.address.city = 'Changsha' let vm = new Vue ({el: "# app", data: {user: {name: "Emperor",} search: "", results: [],} Methods: {fun: function () {alert ("111") }} watch: {/ / use the function search: function (v1, v2) {console.log ('new value:% s, old value:% slots, v1, v2) this.results.push (v1)}) 5, the difference from computed
Trigger conditions are different
The computed calculation property depends on the data property that uses it, and the custom re-invokes the calculation property to execute once as long as the value of the dependent data property changes.
Watch automatically calls the watch callback function when the value of the monitored data attribute changes.
Different application scenarios
Perform asynchronous operations, expensive operations, avoid blocking the main thread, use watch.
Simple and serial return, using computed
Thank you for reading, the above is the content of "listeners in vue, what is the difference between cache and computed". After the study of this article, I believe you have a deeper understanding of what is the difference between listeners, cache and computed in vue. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.