Data vs Computed vs Watcher in Vue Components
There are three main ways to store variables and/or react to variable changes in Vue components. data computed Watch for changes in watcher So, how to decide when to use what? (that is 3-in-1 question, I outwit myself) Although these sections look similar, they serve different functions. Evaluate the variables against the following considerations when you are in doubt. Description Data Computed Watcher Store variables Store local variables Computed variables. Can be static, derived from other variables, or can be static functions Does not store variables - only watches them. React to variable value changes Y Y Y Cached? Y Y N/A Scope Local to component Local to component, but can derive/make calculations with variables from props, store, etc. Can watch local or store variables and react to changes Can be referred by <template> Y e.g. {{ myName }} Y {{ myCalcName }} N/A Can be referred by <script> methods Y this.myName Y this.myCalcName N/A Perform action when value changes N N Y Consequence of a value change Change UI to react to change Change UI Perform action - local/vuex Can change other variable values N Y Y See examples below. ...