自定义事件分发.
使用
this.$emit
进行自定义事件的分发:通过这个可以使用组件调用 vm对象的方法
template: '<li> <button @click="remove">删除</button></li>'
- 组件内的模板,其中
@click="remove"
自定义事件,事件名叫remove组件中的方法
methods:{ remove:function (index) { this.$emit('remove',index); } }
this.$emit('remove',index);
remove:自定义事件名
index:vm传递来的参数
@remove="removeItem(index)"
- 自定义事件绑定vm对象方法
vm对象中对应的方法
methods: { removeItem: function (index) { this.items.splice(index,1);//删除一个元素 按索引 } }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自定义事件分发</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.js"></script>
</head>
<body>
<div id="app">
<todo>
<todo-title slot="slot1" :title="title"></todo-title>
<todo-item slot="slot2" v-for="(item,index) in items" :item="item" :index="index" @remove="removeItem(index)" :key="index"></todo-item>
</todo>
</div>
<script>
Vue.component('todo',{
template: '<div>' +
'<slot name="slot1"></slot>'+
'<ul>' +
'<slot name="slot2"></slot>' +
'</ul>' +
'</div>'
});
Vue.component('todo-title',{
props:['title'],
template: '<p>{{title}}</p>'
});
//加一个删除按钮 并且绑定自定义事件
Vue.component('todo-item',{
props:['item','index'],
template: '<li>{{item}} <button @click="remove">删除</button></li>',
methods:{
remove:function (index) {
this.$emit('remove',index);
}
}
});
var vm = new Vue({
el:"#app",
data:{
title:"前后端学习",
items:['<h1>java</h1>','vue','liuyou']
},
methods: {
removeItem: function (index) {
this.items.splice(index,1);//删除一个元素 按索引
}
}
});
</script>
</body>
</html>