“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

The benefits of the computed

It is very convenient to write expressions in a template, but too much logic in a template can make the template too heavy to maintain

I think the template should be as clean and tidy as possible, what data is needed, how it needs to be presented, using a single word and putting it on the template. It is also officially stated that you should use computed properties for any complex logic. Using computed attributes also makes it easy to extend without changing the template frequently, and only one change is needed when multiple applications are used.

We can define the same function as a method rather than a calculated property. The end result is exactly the same. The difference, however, is that the calculated properties are cached based on vUE’s responsiveness. They are reevaluated only if the correlation response has changed. But functions don’t, so I’m going to write some demos to verify that.

Comparison of computed and methods

If you call computed twice and methods twice on your page, you’ll see that computed only gets called once and methods gets called twice, and that’s the benefit of computed.

<div id="app">
    <p>{{msg}}</p>
    <div>{{comMsg}}</div>
    <div>{{comMsg}}</div>
    <div>{{metMsg()}}</div>
    <div>{{metMsg()}}</div>
  </div>
  <script src=".. /.. /dist/vue.js"></script>
  <script>
    new Vue({
      el: '#app'.data: {
        msg: 'hello vue'
      },
      computed: {
        comMsg() {
          console.log('computed')
          return `The ${this.msg}computed`}},methods: {
        metMsg() {
          console.log('methods')
          return `The ${this.msg}methods`}}})</script>
Copy the code

So, I have a feeling that if we use a concatenated value in multiple places during initialization, we can use computed to do optimization, and the same thing if we have a subsequent update, computed only does one, and methods does two

<button @click="changeMsg"< div style = "box-sizing: border-box; color: RGB (74, 74, 74);changeMsg() {
      this.msg = '666'}}Copy the code

So when I click on the change MSG button, you can see, on the console side, methods still executes twice, computed executes once.

The importance of caching

Why do we need caching? Suppose we have A computationally expensive property, A, that iterates through A large array and does A lot of computations. And then we might have other computational properties that depend on A. Without caching, we would inevitably execute A’s getter multiple times! If you don’t want caching, use methods instead.