javascript - 为什么 v-bind 属性不能正常工作?
问题描述
所以我正在使用 VueJS 创建一个简单的待办事项列表应用程序:
<template>
<div>
<br/>
<div id="centre">
<div id="myDIV" class="header">
<h2 style="margin:5px">My To Do List</h2>
<input type="text" id="myInput" v-model="text" v-on:keyup.enter="AddNote()" placeholder="Title...">
<span v-on:click="AddNote()" class="addBtn">Add</span>
</div>
<ul id="myUL">
<li v-on:click="ToggleClass(index)" v-for="(item, index) in array" v-bind:class="{ checked: isChecked[index] }">
{{item}}
<span class="close">×</span>
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
name: "Notepad",
data() {
return {
array: [],
text: "",
isChecked: []
}
},
methods: {
AddNote: function() {
if(this.text!=="") {
this.array.push(this.text);
this.isChecked.push(false);
this.text = "";
}
},
ToggleClass(index) {
console.log(index);
this.isChecked[index]=!this.isChecked[index];
console.log(this.isChecked);
}
}
}
</script>
但是,当我单击一个项目时,当我单击它时 v-bind 属性不会绑定该类。相反,当我在上面的文本字段中输入内容时,它会绑定它。
有人可以帮忙吗?
解决方案
数组不是响应式的isChecked
,vue 无法检测到更改。您必须触发它,例如通过$set
或splice
。
在此处阅读更多信息:https ://vuejs.org/v2/guide/list.html#Caveats
您可以像这样更改代码:
ToggleClass(index) {
console.log(index);
this.isChecked.splice(index, 1, !this.isChecked[index])
// or this.$set(this.isChecked, index, !this.isChecked[index])
console.log(this.isChecked);
}
推荐阅读
- javascript - 如何根据关键字从文本中获取数据
- python-2.7 - pip 不安全平台且未安装 python 2.7 包
- python - 查找子序列的字符在字符串中的位置并在列表中返回
- javascript - 理解 DOM 中接口和对象的区别
- android - 在 Ionic 5 中找不到电容器社区/sqlite 的 GlobalSQLite 文件
- r - R中的递归优化()函数会导致错误
- qt - QT 5.12.x及以上版本是否支持OpenGL稀疏纹理特性-ARB_sparse_texture-调用glTexPageCommitmentARB()
- android - 带有 Firestore 回收器视图的动画不起作用
- django-rest-framework - djangorestframework-simplejwt 得到“没有找到具有给定凭据的活动帐户”虽然我知道我的用户存在
- python - Python:加速函数调用