javascript - 在 Vue.js 中单击按钮时清除文本字段?
问题描述
我有一个布局,我正在循环获取文本字段和一个按钮。我如何在按钮上添加一个功能,以便它只清除它各自的字段。在这里查看小提琴。
<div id="app">
<h2>Each text with it's own state and clear should clear the respective
text fields</h2>
<ul v-for="todo in todos">
<li>
<input type="text" :placeholder="`${todo.text}`">
</li>
<li>
<input type="text" :placeholder="`${todo.text1}`">
</li>
<button>Clear</button>
</ul>
new Vue({
el: "#app",
data: {
todos: [
{ text: "Learn JavaScript", text1:"Hey" },
{ text: "Learn Vue", text1:"Hello" },
{ text: "Play around in JSFiddle", text1:"Ciao" },
{ text: "Build something awesome", text1:"Something"}
]
}
})
解决方案
如果要清除特定字段,可以添加一个clear
将索引作为参数的方法,但在此之前,您应该向每个字段添加value
和value1
项目todo
并将它们绑定到字段,如下所示:
new Vue({
el: "#app",
data: {
todos: [{
text: "Learn JavaScript",
text1: "Hey",
value1:'',
value:''
},
{
text: "Learn Vue",
text1: "Hello",
value1:'',
value:''
},
{
text: "Play around in JSFiddle",
text1: "Ciao",
value1:'',
value:''
},
{
text: "Build something awesome",
text1: "Something",
value1:'',
value:''
}
]
},
methods:{
clear(i){
this.todos[i].value='';
this.todos[i].value1='';
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<h2>Each text with it's own state and clear should clear the respective text fields</h2>
<ul v-for="(todo,i) in todos">
<li>
<input type="text" :placeholder="`${todo.text}`" v-model="todo.value">
</li>
<li>
<input type="text" :placeholder="`${todo.text1}`" v-model="todo.value1">
</li>
<button @click="clear(i)">Clear</button>
</ul>
</div>
推荐阅读
- apache-spark - k8s 上 JupyterHub 笔记本上的 Apache Spark 远程集群
- python - Python multiprocessing.Queue 在传递 ctype 对象时停止
- oracle - 与 Oracle 源相比,注入 SQL DB 的数据太大
- api - 如何调试 Word OfficeJs 仅命令加载项
- python - 如何将预测的类别和概率与实际标签相匹配
- reactjs - 反应路由器dom的链接无法正常工作
- mysql - MYSQL:连接到 localhost 和 host.docker.internal
- python - 在python中将opencv图像写入zip文件
- java - 如何从 InnerClass 访问 OuterClass 字段?
- python - 从python字典中获取值并一一传递