子视图模型函数触发父视图模型computed的原因及执行差异问询
Hey there! Let's unpack your two questions clearly—this all boils down to how Vue's reactivity system operates behind the scenes.
问题1:为何子视图模型中的函数会触发父视图模型中的computed执行?
Vue's computed properties work on a dependency tracking system. When you define a computed property in the parent view model, Vue automatically keeps track of all reactive data properties that the computed uses to calculate its value.
Now, if the function in your child view model modifies any of those tracked reactive properties (this could be direct access like this.$parent.someData, indirect changes via props bound to parent data, or even through shared reactive state), Vue's reactivity system detects that change. Once it does, it knows the computed property's value is no longer valid, so it re-runs the computed function to update the result.
For example: if your parent has a data property totalItems, and a computed totalPrice that multiplies totalItems by item price, a child function that runs this.$parent.totalItems += 1 will trigger totalPrice to recalculate automatically.
问题2:点击按钮执行嵌套视图模型函数,触发父computed;但computed改普通函数后点击不执行,为什么?
The key difference here lies in how Vue handles computed properties versus regular functions:
- Computed properties are reactive and dependency-driven: As I noted earlier, Vue automatically tracks every reactive data property that the computed relies on. When any of those dependencies change, Vue will re-run the computed function automatically to update its value (and it caches the result until dependencies shift again).
- Regular functions are call-driven: A regular function has no built-in reactivity tracking. It only executes when you explicitly call it—Vue won’t trigger it just because some reactive data it uses has changed.
In your original setup, the child’s function modifies a reactive property that the parent’s computed depends on, so the computed runs automatically. When you swap that computed for a regular function, there’s no code in your button click handler that calls this function. So only the child’s function runs, and the parent’s regular function won’t execute unless you explicitly invoke it as part of the click event flow.
内容的提问来源于stack exchange,提问作者OfirD

