Vue.js解构默认参数时this引用data数据的问题求助
this Reference Issue in Destructured Default Parameters for Vue Methods Hey there! Let's break down why you're hitting that TypeError and fix it step by step.
The Root Cause
When you try to use this inside the destructured parameter's default value like this:
fillData ({ must = this.chartData.distributionInitialData, nice = this.chartData.distributionInitialData }) { ... }
The this here doesn't point to your Vue component instance!
Parameter default value expressions are evaluated in the parameter scope of the function, not the function body scope. In strict mode (which Vue enables for component methods by default), this in this scope is undefined. That means this.chartData throws an error, which breaks the destructuring process entirely—hence the "Cannot read property 'must' of undefined" message.
The Solution
Move the destructuring into the function body, where this correctly references your Vue instance:
methods: { fillData (options = {}) { // Destructure inside the function body, using `this` for defaults const { must = this.chartData.distributionInitialData, nice = this.chartData.distributionInitialData } = options // Now your operation code will work as expected // ... your original logic here } }
How This Works
- We set a default empty object for the
optionsparameter, so even if you callfillData()without arguments, destructuring won't fail. - Inside the function body,
thisis properly bound to your Vue component instance (Vue automatically does this for methods), so you can safely accessthis.chartData.distributionInitialDataas the fallback value formustandnice.
Bonus: Simplify If Defaults Are Identical
Since both must and nice use the same default value, you can clean this up a bit to avoid repetition:
fillData (options = {}) { const defaultData = this.chartData.distributionInitialData const { must = defaultData, nice = defaultData } = options // ... rest of your code }
内容的提问来源于stack exchange,提问作者jean d'arme

