In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge of how to deal with computed in Vue+TypeScript. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
What is "computed"?
"computed" is a calculation property provided in Vue. It is mixed into the Vue instance, and the this context of all getter and setter is automatically bound to the Vue instance. The results of the evaluated properties are cached and recomputed unless the dependent responsive property changes.
The use of "computed"
We can use "computed" to process the existing attribute data to get our target data.
How to use it in TypeScript
In "vue-class-component", corresponding decorators are provided for props,watch, etc., while "computed" does not have a corresponding decorator.
In the example of the official website, the function of "computed" is realized through "get".
Import Vue from 'vue'import Component from' vue-class-component' @ Componentexport default class HelloWorld extends Vue {firstName = 'John' lastName =' Doe' / / Declared as computed property getter get name () {return this.firstName +'+ this.lastName} / / Declared as computed property setter set name (value) {const splitted = value.split ('') this.firstName = splitted [0] this.lastName = splitted [1] | |'}} another option
In the actual project, after the component is changed to TypeScript, the calculation properties are implemented using get, and the browser console prompts that data is non-responsive and the data cannot be displayed. Component js version
Export default {name: 'hierarchy-table', props: {value: {type: Array, required: true}, skipCodes: {type: Array}}, data () {return {};}, computed: {data () {return this.skipCodes? This.value.filter (it = >! this.skipCodes.includes (it.code)): this.value;}}, methods: {selectChange (selection) {this.$emit ('selection-change', selection);}
In view of this problem, it is solved by creating intermediate variables. Component ts version
Import {Component, Prop, Vue, Watch} from 'vue-property-decorator'; @ Componentexport default class HierarchyTable extends Vue {data: any [] = []; @ Prop ({type: Array, required: true}) valuevaluation: any; @ Prop ({type: Array}) skipCodes: any; @ Watch (' value') valueChanged (val) {this.updateData ();} @ Watch ('skipCodes') skipCodesChanged () {this.updateData () } updateData () {this.data = this.skipCodes? This.value.filter (it = >! this.skipCodes.includes (it.code)): this.value;} selectChange (selection) {this.$emit ('selection-change', selection);}} correct use of vue computed
In a recent interview, I met a young man who talked about the difference between computed and watch in vue, and finally got a stunning answer, using only watch and never using computed.
Expressions within templates are very convenient, but they are originally designed for simple operations. Putting too much logic in a template can make the template overweight and difficult to maintain, so vue advocates the use of computational attributes for complex logic. Special note: the getter function for evaluating properties has no side effect, which makes it easier to test and understand-from Vue calculated properties
Before we discuss the difference between computed and watch, let's take a look at the difference between computed and methods.
Computed or methods
In theory, all implementations of computed can be completely replaced with methods.
Reversed message: "{{reversedMessage ()}}"
Reversed message: "{{reversedMessage}}"
/ / calculate attribute computed: {reversedMessage () {return this.message.split ('') .reverse () .join ('')}} / / method methods: {reversedMessage: function () {return this.message.split ('') .reverse () .join ('')}}
Calculated properties are cached based on their responsive dependencies. They are re-evaluated only when the correlation response dependency changes. This means that as long as the message has not changed, multiple visits to the reversedMessage calculation property will immediately return the previous calculation results without having to execute the function again. And the method will be executed.
This also means that the following calculation properties will no longer be updated because Date.now () is not a responsive dependency:
Computed: {now: function () {return Date.now ()}}
Why do we need caching? Suppose we have a computational attribute A with high performance overhead, which needs to traverse a large array and do a lot of calculations. Then we may have other computational properties that depend on A. If there is no cache, we will inevitably execute A's getter many times! If you don't want to have a cache, please use a method instead.
What they have in common: computed and methods will be mixed into the Vue instance. Vm.reversedMessage/vm.reversedMessage () can get the relevant calculation properties / methods.
Next, what's the difference between computed and watch?
Computed or watch
Vue provides a more general way to observe and respond to data changes on Vue instances: listening for properties. It is easy to abuse watch when you have some data that needs to change with other data changes. However, it is usually better to use computational properties rather than imperative watch callbacks.
The watch approach is most useful when you need to perform asynchronous or expensive operations when the data changes. It 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. These are things that computational properties cannot do.
Methods: {getAnswer: function () {this.answer = 'Thinking...' Var vm = this axios.get ('https://yesno.wtf/api'). Then (function (response) {vm.answer = _ .capitalize (response.data.answer)}) .catch (function (error) {vm.answer =' Error! Could not reach the API.'+ error})}}, created: function () {/ / debounce bounce function this.debouncedGetAnswer = _ .debounce (this.getAnswer, 500)}
From this point of view, watch can completely replace computed? Under what circumstances can you only use computed?
In retrospect, the most important feature of computed is caching, so the above question can be translated into: under what circumstances do we need to rely on caching?
Example: the parent component passes a value to the child component, and the value type is a reference type
Parent component
Parent: import Child from'. / child.vue'export default {data () {return {user: {name: 'ligang'}, components: {Child}}
Sub-component
Child: {{user}} export default {name: 'child', props: [' user']}
There is now a requirement that both pre-and post-change values need to be displayed in the subcomponents.
So Easy, you just need to save the oldVal in watch.
Child: before modification: {{oldUser}} after modification: {{user}} export default {name: 'child', props: [' user'], data () {return {oldUser: {}, watch: {user: {handler (val, oldVal) {this.oldUser = oldVal | val}, deep: true, immediate: true}
Check the results, WTF, what's going on?
The problem is that user is a reference type and watch is not cached, resulting in the modification of the same object, so * * val = olVal is trueworthy in the watch method! **
How to meet the requirements, here we can borrow the features of computed cache to accomplish the above situation.
The result of the calculated property is cached and will not be recalculated unless the dependent responsive property changes. Note that if a dependency (such as a non-responsive property) is outside the scope of the instance, the calculated property will not be updated. -vue-computed-api
Child: before modification: {{oldUser}} after modification: {{user}} export default {name: 'child', props: [' user'], data () {return {oldUser: {}, / / userInfo computed: {userInfo () {return {... this.user}, watch: {userInfo: {handler (val) OldVal) {this.oldUser = oldVal | | val}, deep: true, immediate: true}
Note: {... this.user} or use Object.assign ({}, this.user) to create a new reference!
These are all the contents of the article "how to deal with computed in Vue+TypeScript". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.