创建一个工程文件:
css中引用的是bootstrap的css,js中就是vue,index页面:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>vue2.0</title> <link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"> </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container" id="app"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">welcome Vue 2.0</div> <div class="panel-body"> <input type="text" name="" v-model="message" class="form-control"> <h1>{{message}}</h1> <ul class="list-group"> <li class="list-group-item" v-for="(todo,index) in todos"> {{todo.title}} <button class="btn btn-warning btn-xs pull-right" v-on:click="deleteTodo(index)">Delete</button> </li> </ul> <form v-on:submit.prevent="addTodo(newTodo)"> <div class="form-group"> <input type="text" name="" class="form-gcontrol" placeholder="add a new todo" v-model="newTodo.title"> </div> <div class="from-group"> <button class="btn btn-success" type="submit">add todo</button> </div> </form> </div> </div> </div> </div> </div> <script type="text/javascript" src="js/vue.js"></script> <script type="text/javascript"> new Vue({ el:'#app', data:{ message:'hello world', todos:[ {id:1,title:"learn vuejs"}, ], newTodo:{id:null,title:""}//定义一个obj }, methods:{ addTodo(newTodo){//es6 this.todos.push(newTodo);//把新的obj添加在数组中, this.newTodo = {id:null,title:""}//初始化newTodo }, deleteTodo(index){ this.todos.splice(index,1);//删除下标为index的元素 } } }); </script> </body> </html>
这里的v-on:submit.prevent="addtodo(newTodo)"(这里的prevent是用来阻止form的默认提交行为,否则点击btn会有一个提交行为报错),methods里面定义一些方法。
input输入框一定绑定newTodo,这里不加this.newTodo = {id:null,title:""}的时候我点击按钮多次添加的是同样的内容,并且再次改变input的时候所有之前添加的都会改变,这是什么情况?不是已经添加到todos里了么,希望有朋友点拨一下。
v-for里面要把index参数传递进去。
arrayObject.splice(index,howmany,item1,.....,itemX)
参数 | 描述 |
index | 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置 |
howmany | 必需。要删除的项目数量。如果设置为 0,则不会删除项目 |
item1, ..., itemX | 可选。向数组添加的新项目 |