This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging

Image taken from official document. The interpretation and use scenarios for computed in the official documentation seem simple and clear, but in real development, I know computed is a computing attribute, but when do I use it? As the official example (split, reverse, concatenation string), in the actual development process, this function is estimated that no one will use the computed properties, generally in the methods of processing directly. For a long time, I’ve written vUE projects that have never used computed, to the point where I question it. Until one day, there was a requirement in the project, which made me realize the power of this attribute for the first time!

I have simply written a demo to discuss the use of the attribute computed

The parent component

Child components

As you can see, the parent component passes an array to the child component. The child component props receives the array and modifs it. The console did not report an error, but as we all know, this is not recommended in VUE. In this case, we can use computed and use the concat() method of the array to compute a new value for the subcomponent. In this case, no matter how much we modify the myList data in the subcomponent, the list data in the subcomponent will remain the same! Of course, this method for handling arrays can also be placed in Mounted or methods, but remember this! Computed attributes are cached based on their responsive dependencies. In demo’s case, myList in the child component is recalculated only when the list in the parent component changes. Of course, in this example, there are only two pieces of data in the array, but in a real development environment, there would be a lot of data in the array, so the computed attribute is appropriate here

Calculates the getter and setter for the property

    computed:{
        // This function must return a value as an initial value
        test(){
            reutrn xxx
        }
    }
Copy the code
    computed:{
       // The complete method of calculating the property (get must be written, set should be written when needed)
       test: {get(){
               // Get the current value of test
               return xxx
           },
           set(val){
               // The setter is fired when the test value is changed. Val is the changed value}}}Copy the code