Are methods in Vue reactive?

前端 未结 3 1851
后悔当初
后悔当初 2021-01-02 01:38

I\'ve been using Vue for a while, and my experience has always been a method will recompute if its underlying reactive data is updated. I\'ve encountered conflicting informa

3条回答
  •  攒了一身酷
    2021-01-02 02:01

    This is a very interesting case.

    From what I have read and my experience I can say that: No, methods are not inherently reactive. A method must be explicitly called for it to execute.

    But, then how can I explain your case? I put your code in in a sandbox and sure enough, as you push id's into the array, the template updates to display the animal name. This would indicate some reactivity. What gives?

    Well, I ran an experiment. I added a simple div to each loop that generates a random number when generated.

  • {{ random() }}
    {{ animal.name }}
  • ... random() { return Math.random(); }

    And what I saw was that every time a new id was pushed into the array, all the random numbers would change. This is the key to understand why it "seems" as though the method isAwesome is reactive.

    Somehow, when a new ID is pushed to the array, Vue re-renders the loop entirely, hence executing the methods again. I can't explain the inner workings of why vue re-renders the entire loop, that would require further research.

    So to answer your question. isAwesome is not reactive, it is merely an illusion created by the re-render of the loop.

提交回复
热议问题