<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>veuIndex</title> <script type="text/javascript" src="js/vue.min.js"></script> </head> <body> <div id="root"> <div> <input v-model="inputValues"/> <button @click="handleSubmit">提交</button> <todo-item v-for="(item,index) of list" :key="index" :content="item" :index = "index" @delete = "handleDelete"></todo-item> <todo-item2></todo-item2> </div> </div> <script> //全局组件 Vue.component('todo-item', { props: ['content', 'index'],//组件接受一个从外部传进来的content值,即:content的值 template: '<li @click="componentClick">{{content}}{{index}}</li>',//{{content}}即props中定义的content,若不定义则无法使用 methods: { componentClick: function () { this.$emit('delete',this.index);//用来对应@delete,然后@delete里的方法定义在父组件的merthods中 } } }); //局部组件 var TodoItem = { template: '<li>itme2</li>' }; new Vue({ el: "#root", components: { 'todo-item2': TodoItem }, data: { list: [], inputValues: '' }, methods: { handleSubmit: function () { this.list.push(this.inputValues); this.inputValues = ''; }, handleDelete : function (index) { this.list.splice(index,1);//删除对应下标开始的一项 } } }) </script> </body> </html>