
在 Vue.js 中,可通过方括号语法 this[key] 动态读写响应式 data 属性,但双中括号 [[key]] 是非法 JavaScript 语法,必须改为单层方括号 this[key],并确保传入字符串形式的属性名。
在 vue.js 中,可通过方括号语法 `this[key]` 动态读写响应式 data 属性,但双中括号 `[[key]]` 是非法 javascript 语法,必须改为单层方括号 `this[key]`,并确保传入字符串形式的属性名。
Vue.js 的响应式系统依赖于对 this 上属性的合法访问。你尝试使用的 this[[inputBoxTextIdentifier]] 写法在 JavaScript 中完全无效——[[...]] 并非合法语法(既不是数组字面量,也不是模板字符串或可选链),浏览器会直接抛出 SyntaxError。
✅ 正确做法是:将属性名作为字符串传递,并使用标准的方括号属性访问器 this[key]:
const app = Vue.createApp({
data() {
return {
firstInputBoxTextValue: "",
secondInputBoxTextValue: ""
};
},
methods: {
showAlert() {
alert("Button has been clicked..!");
},
updateInputBoxText(event, inputBoxTextIdentifier) {
// ✅ 正确:inputBoxTextIdentifier 必须是字符串,如 'firstInputBoxTextValue'
this[inputBoxTextIdentifier] = event.target.value;
}
}
});同时,HTML 模板中调用时需显式传入带引号的字符串字面量,而非未加引号的变量名(否则 Vue 会尝试查找名为 firstInputBoxTextValue 的局部变量,而该变量并不存在):
<!-- ❌ 错误:firstInputBoxTextValue 被当作变量解析(未定义) -->
<input type="text" @keydown="updateInputBoxText($event, firstInputBoxTextValue)" />
<!-- ✅ 正确:用单引号包裹,传入字符串 -->
<input type="text" @keydown="updateInputBoxText($event, 'firstInputBoxTextValue')" />
<p>OUTPUT: {{ firstInputBoxTextValue }}</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill13436" title="Json To Jianying Description"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20cf0281539.jpg" alt="Json To Jianying Description" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill13436" title="Json To Jianying Description">Json To Jianying Description</a>
<p>将包含oralBroadcastingList、materialList、bgmInfo等字段的JSON视频素材转换为剪映API可用的自然语言描述,用于生成视频制作指令,包括素材匹配、时间轴计算、字幕同步、特殊效果处理等。</p>
</div>
<a href="/xiazai/skill13436" title="Json To Jianying Description" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/cb6835dc7db1" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">前端免费学习笔记(深入)</a>”;</p>
<input type="text" @keydown.enter="updateInputBoxText($event, 'secondInputBoxTextValue')" />
<p>OUTPUT: {{ secondInputBoxTextValue }}</p>⚠️ 注意事项:
-
this[key]能正常触发 Vue 的响应式更新,前提是key对应的属性已在data()返回对象中预先声明(如示例中的firstInputBoxTextValue)。Vue 3 的ref/reactive机制同样支持动态访问,但需配合unref()或toRaw()等工具谨慎处理。 - 若传入的
inputBoxTextIdentifier拼写错误或属性未定义(如'thirdInputBoxTextValue'未在 data 中声明),赋值虽不会报错,但不会触发视图更新(因非响应式属性)。 - 更现代、推荐的替代方案(尤其 Vue 3 Composition API)是使用
ref+ 解构或reactive对象配合watch,但本例中 Options API 下this[key]是简洁且符合 DRY 原则的标准解法。
总结:动态更新 data 属性的核心是「字符串键 + 方括号访问」,去掉多余的中括号,确保模板中传参为字符串字面量,即可安全、高效地复用方法逻辑。

















