
Vue.js 不支持 this[[key]] 这种双重方括号语法;正确方式是使用中括号属性访问符 this[key],配合字符串形式的属性名实现动态赋值。
vue.js 不支持 `this[[key]]` 这种双重方括号语法;正确方式是使用中括号属性访问符 `this[key]`,配合字符串形式的属性名实现动态赋值。
在 Vue 3(Composition API 或 Options API)中,若需根据运行时传入的字符串动态读写 data 响应式属性(如 firstInputBoxTextValue 或 secondInputBoxTextValue),必须使用标准 JavaScript 的方括号表示法 this[key],而非错误的 this[[key]] —— 后者在 JavaScript 中语法非法,会直接抛出 SyntaxError: Invalid bracket notation。
✅ 正确用法:动态属性赋值
将模板中调用改为传递属性名字符串(注意加引号):
<input type="text" v-on:keydown="updateInputBoxText($event, 'firstInputBoxTextValue')"><input type="text" v-on:keydown.enter="updateInputBoxText($event, 'secondInputBoxTextValue')">
对应方法中使用合法的中括号访问:
methods: {
showAlert() {
alert("Button has been clicked..!");
},
updateInputBoxText(event, inputBoxTextIdentifier) {
// ✅ 正确:inputBoxTextIdentifier 是字符串,如 'firstInputBoxTextValue'
this[inputBoxTextIdentifier] = event.target.value;
}
}
⚠️ 注意事项:
Json To Jianying Description下载将包含oralBroadcastingList、materialList、bgmInfo等字段的JSON视频素材转换为剪映API可用的自然语言描述,用于生成视频制作指令,包括素材匹配、时间轴计算、字幕同步、特殊效果处理等。
inputBoxTextIdentifier必须是字符串字面量(如'firstInputBoxTextValue'),不能是未加引号的变量名(如firstInputBoxTextValue),否则会被当作变量查找,导致undefined或 ReferenceError;- Vue 3 的响应式系统能正确追踪
this[key]赋值(前提是key对应的属性已在data()中声明),无需额外处理;- 若需增强健壮性,可添加存在性校验:
updateInputBoxText(event, inputBoxTextIdentifier) { if (inputBoxTextIdentifier in this) { this[inputBoxTextIdentifier] = event.target.value; } else { console.warn(`Data property "${inputBoxTextIdentifier}" not found.`); } }
? 更进一步:DRY 优化建议(可选)
若字段较多,还可结合 v-model 实现更简洁、声明式的双向绑定(推荐 Vue 风格):
<input v-model="firstInputBoxTextValue"><input v-model="secondInputBoxTextValue">
此时无需手动操作 event.target.value,逻辑更清晰、不易出错。
总之,this[[key]] 是无效语法;坚持使用 this[key],并确保 key 为字符串,即可安全、高效地实现动态数据绑定,真正践行 DRY 原则。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











