<script> let app=new Vue({ el:'#app', data:{ id:0, name:'', books:[ {'id':1,'name':'Vue.js入门','time':new Date()} ], isEditable:true }, mounted(){ this.id=this.books.length+1 console.log(this.id) }, methods:{ onchange(){ if(this.name!=''){ this.isEditable=false } else{ this.isEditable=true } }, add:function (){ for(let i=0;i<this.books.length;i++){ if(this.books[i].name===this.name){ console.log("该书已经存在") return } } this.books.push({'id':this.id,'name':this.name,'time':new Date()}) this.id++ this.name='' console.log(this.books) }, del(id){ let index=this.books.findIndex((item)=>{ if(item.id==id){ return true } }) this.books.splice(index,1) }, } })在这个代码中增加edit这个函数实现修改图书名字的功能
时间: 2024-02-10 13:15:20 浏览: 39
好的,这里是一个修改图书名字的示例代码:
```
<script>
let app=new Vue({
el:'#app',
data:{
id:0,
name:'',
books:[
{'id':1,'name':'Vue.js入门','time':new Date()}
],
isEditable:true
},
mounted(){
this.id=this.books.length+1
console.log(this.id)
},
methods:{
onchange(){
if(this.name!=''){
this.isEditable=false
}
else{
this.isEditable=true
}
},
add:function (){
for(let i=0;i<this.books.length;i++){
if(this.books[i].name===this.name){
console.log("该书已经存在")
return
}
}
this.books.push({'id':this.id,'name':this.name,'time':new Date()})
this.id++
this.name=''
console.log(this.books)
},
del(id){
let index=this.books.findIndex((item)=>{
if(item.id==id){
return true
}
})
this.books.splice(index,1)
},
edit(id) {
let index=this.books.findIndex((item)=>{
if(item.id==id){
return true
}
})
this.books[index].name = prompt('请输入新的图书名称', this.books[index].name);
},
}
})
</script>
```
在上面的代码中,我们增加了一个edit函数,用来实现修改图书名称的功能。这个函数接收一个id参数,表示需要修改的图书的id。首先,我们通过findIndex函数找到需要修改的图书在books数组中的位置。然后,我们使用prompt函数弹出一个提示框,让用户输入新的图书名称。最后,我们将新的图书名称赋值给books数组中对应位置的name属性,从而完成图书名称的修改。