11. 自定义事件内容分发
如slot
示例代码中,如何通过操作组件删除掉ViewModel的源数据代码呢?
ViewModel自己通过method删除DOM
<script>
var vm = new Vue({
el : "#app",
data : {
title : '选择你的英雄',
items : ['高等数学','线性代数','摆烂']
},
methods : { //ViewModel的方法
removeItems : function(index){
console.log("删除了"+this.items[index]+"OK");
this.items.splice(index,1); //js函数,删除元素 删除items的第index个元素
//splice删除函数 splice(删除元素的索引,从索引开始要删除的元素个数,要替换的新索引)
}
}
})
</script>
再组件里面去操作ViewModel中的数据 (通过props传值与自定义事件)
自定义事件 this.$emit(‘自定义事件名’,参数)
<body>
<!--
1.要删除ViewModel中的data,必须使用ViewModel中的方法,因此问题就变为:如何使用组件中的方法调用ViewModel中的方法即removeItems
2.再标签中通过 v-on(@)可以绑定ViewModel中的函数,因此使用@来将removeItems(index)绑定到组件中的自定义事件remove
3.在组件的methods中需要定义方法remove(index) , 其中调用自定义事件 this.$emit('remove',index);
-->
<div id="app">
<slot>
<slot-title slot="slot-title" :title="title"></slot-title>
<
<slot-items slot=slot-item" v-for="(item,index) in items" :item="item" :index="index"
@remove="removeItems(index)"></slot-items>
</slot>
</div>
<script>
Vue.component('slot',{
template : '<div>' +
'<slot name="slot-title"></slot>' + //插槽slot
'<ul>' +
'<slot name="slot-item"></slot>' + //插槽slot
'</ul>' +
'</div>'
});
Vue.component('slot-title',{
props : ['title'],
template : '<div>{{title}}</div>'
});
Vue.component('slot-items',{
props : ['item','index'],
template : '<li>{{index}}->{{item}}<button @click="removeFun">删除</button></li>',
methods: {
removeFun: function (index){
this.$emit('remove',index);
}
}
});
var vm = new Vue({
el : "#app",
data : {
title : '选择你的英雄',
items : ['高等数学','线性代数','摆烂']
},
methods : {
removeItems : function(index){
this.items.splice(index,1);
}
}
})
</script>
</body>
- 要删除ViewModel中的data,必须使用ViewModel中的方法,因此问题就变为:如何使用组件中的方法调用ViewModel中的方法即removeItems
- 再标签中通过 v-on(@)可以绑定ViewModel中的函数,因此使用@来将removeItems(index)绑定到组件中的自定义事件remove , 这个时候remove事件是一个自定义事件,通过remove可以调用removeItems(),但是remove依然没有能够与组件产生联系
- 在组件的methods中定义方法 removeFun(index) , 在其中调用自定义事件 this.
e
m
i
t
(
′
r
e
m
o
v
e
′
,
i
n
d
e
x
)
,
并
将
r
e
m
o
v
e
F
u
n
绑
定
到
自
己
的
模
板
的
‘
B
u
t
t
o
n
‘
上
,
这
样
通
过
‘
B
u
t
t
o
n
‘
的
点
击
事
件
就
能
够
=
=
先
调
用
自
己
的
r
e
m
o
v
e
F
u
n
(
i
n
d
e
x
)
方
法
,
然
后
r
e
m
o
v
e
F
u
n
(
i
n
d
e
x
)
调
用
‘
emit('remove',index) , 并将removeFun绑定到自己的模板的`Button`上,这样通过`Button`的点击事件就能够==先调用自己的removeFun(index)方法,然后removeFun(index) 调用 `
emit(′remove′,index),并将removeFun绑定到自己的模板的‘Button‘上,这样通过‘Button‘的点击事件就能够==先调用自己的removeFun(index)方法,然后removeFun(index)调用‘.emit(‘remove’,index)
方法 ,remove(自定义方法)再去调用ViewModel中的removeItems(index)方法== , 当然,前提条件是 通过
v-bind(:)绑定并通过
props正确传入了参数
index`。