vue基础学习-自定义事件分发
Vue this.$emit(‘事件名’,‘参数数据’)
官网
记录学习的一些问题,组件如何对Vue对象的数据进行删除。涉及到参数传递与事件分发。
- 在vue的实例中增加了methods对象并定义了一个名为removeTodoltems的方法
//2.定义数据
new Vue({
el:"#vue",
data:{
message:"你好",
title:"自定义组件",
todoItems:['1','2','3']
},
methods:{
removeItem(index){
console.log("删除了"+this.todoItems[index]+"ok")
this.todoItems.splice(index,1)//一次删除一个元素
}
}
});
- 修改todo-items待办内容组件的代码,增加一个删除按钮,并且绑定事件!
// 1.现在自定义一个组件
//这里用反斜杠代替字符串
Vue.component("todo",{
template:`<div>
<slot name="todo-title"></slot>
<ul>
<slot name="todo-items"></slot>
</ul>
</div>`
})
Vue.component("todo-title",{
props:['title'],
template:'<div>{{title}}</div>'
})
Vue.component("todo-items",{
props:['item','index'],
template:'<li>{{item}}---{{index+1}}<button @click="remove">删除</button></li>',
methods:{
remove(index){
this.$emit('remove',index)
}
}
})
- 修改todo-items待办内容组件的HTML代码,增加一个自定义事件,比如叫remove,可以和组件的方法绑定,然后绑定到vue的方法!
<div id="vue">
{{message}}
<todo>
<todo-title slot="todo-title" title="title"></todo-title>
<todo-items slot="todo-items" v-for="(item,index) in todoItems" :index="index" v-bind:item="item" v-on:remove="removeItem"></todo-items>
</todo>
</div>