gpt4 book ai didi

javascript - 如何将输入的值添加到 li 列表?

转载 作者:行者123 更新时间:2023-12-01 01:16:15 33 4
gpt4 key购买 nike

我正在尝试将输入值添加为 <li><ul>列表。

我可以通过将值绑定(bind)到 lis 的数组列表来添加它。但是,当我清理输入字段时,它不会留在那里。我该如何解决这个问题?

HTML 代码:

<div id="app">
<h1>{{ message }}</h1>
<form v-on:submit.prevent="addNewTodo">
<input type="text" v-model="todo.task">
<button type="submit">Add todo</button>
</form>

<ul>
<li v-for="todo in todos" :class="{ completed: todo.isActive }" @click="$set(todo, 'isActive', !todo.isActive)">
{{ todo.task }} <span v-on:click="deleteTodo">{{ todo.delete }}</span>
</li>
</ul>
</div>

JS 代码:

var app = new Vue({
el: '#app',
data: {
message: 'List of things to do today',
todos: [
{ task: 'Have breakfast', delete:'(x)'},
{ task: 'Go to the gym', delete:'(x)'},
{ task: 'Study Vuejs', delete:'(x)'}
],
todo: {task: '', delete: '(x)'}
},
methods: {
addNewTodo: function(){
this.todos.push( this.todo );
},
deleteTodo: function(){
this.todos.shift( this.todo )
},
}
});

这里有一个 JSfiddle 示例:https://jsfiddle.net/mercenariomode/gwd34815/1/

最佳答案

您需要更改对象引用,但在您的情况下,最好将“v-model”绑定(bind)到“task”属性

HTML 代码:

<form v-on:submit.prevent="addNewTodo">
<input type="text" v-model="task">
<button type="submit">Add todo</button>
</form>

JS 代码:

el: '#app',
data: {
message: 'List of things to do today',
todos: [
{ task: 'Have breakfast', delete:'(x)'},
{ task: 'Go to the gym', delete:'(x)'},
{ task: 'Study Vuejs', delete:'(x)'}
],
task: '',
}

并在addNewTodo方法中实现向数组添加对象的逻辑

addNewTodo: function(){
let todo = {task: this.task, delete: '(x)'};
this.todos.push(todo);

this.task = ''; // clear data in input
},

JSFiddle:https://jsfiddle.net/nm29yq7d/1/

关于javascript - 如何将输入的值添加到 li 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738490/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com