html如下:
<div id="app">
<input type="text" v-model="inputValue"/>
<button @click="handlClick">提交</button>
<ul>
<todo-item v-for="(item,index) in List"
:content="item"
:index="index"
@delete="handleItemDelete"><!--content是定义的组件间传递的变量,@detele监听子组件的delete的handleItemClick事件-->
</todo-item>
</ul>
</div>
js:
var TodoItem = {
props:["content","index"],
template:"<li @click='handleItemClick'>{{content}}</li>",
methods:{
handleItemClick:function(){
this.$emit("delete",this.index) //子组件向父组件传值
}
}
}//注册的是局部组件,需要在对应ID下注册
var app = new Vue({
el:"#app",
components:{
TodoItem: TodoItem //局部组件需要在父组件里面申明,一般申明以对象的形式
},
data: {
List:[],
inputValue:''
},
methods:{
handlClick:function(){
this.List.push(this.inputValue)
this.inputValue = ''
},
handleItemDelete:function(index){
this.List.splice(index,1)
}
}
})
</script>