Home > other >  Manage big computed objects in vuejs
Manage big computed objects in vuejs

Time:10-25

In vuejs it's preferable to keep computed variables small, to reduce the computational effort done each time a dependency changes. So what otherwise would be a big tidy up object with a lot of properties, it's broken into a lot of small computed variables, which in the end of the day it's a mess to read and maintain.

In the other hand, if you make the whole big object as a single computed variable it looks good and it's easy to read and maintain, but every time a single property needs to be updated, all the object gets updated, with the penalty performance it suposes.

So which is the way to go? Messy chunk of computed variables? One big computed object with the performance penalty? Or there is a third way?

CodePudding user response:

I think a good solution is to create all computed variables separately, and then create another one computed variable to collect them into big object.

computed:{
 depA() {...}
 depB() {...}
 depC() {...}
 bigTidyObject(){ //using depA,depB,depC}
}

I think in this case Vue will do only necessary recomputing. E.g. if depB is changed, then only depB will be recomputed, and previously computed values of depA and depC will be used.

You can try out this example:

data() {
    return {
      flag: false,
      flag2: false,
      flag3: false,
      flag4: false,
    };
  },
  computed: {
    flag5() {
      console.log("flag 5 accessed");
      return this.flag3 && this.flag4;
    },
    flag6() {
      console.log("flag 6 accessed");
      return this.flag || this.flag2;
    },
    complexeFlag() {
      console.log("complexe flag accessed");
      return this.flag5 || this.flag6;
    },
  },
  methods: {
    onClick() {
      this.flag = !this.flag;
    },
  },

When you click on Vue logo, only flag6 is accessed, but no flag5.

P.S. If you want to hide dependencies to simplify reading, sometimes moving it into Vue mixins is a good solution. But only when it is semantically acceptable.

  • Related