Vue 中自定义事件内容分发
1.什么是内容分发
纯属说概念的话会过于呆板并且十分抽象不好理解,可以简单的将内容分发理解为在Vue中定义的函数通过传递的方式使得组件通过this.$emit(‘自定义事件名’,param…)进行调用,下面小编举例说明
现在有如下需求:
数据是通过for循环遍历出来的,需要对每个元素点击删除的时候,该对应元素会被删除
2.如何实现内容分发
1.双向绑定自定义数据以及展示数据
Vue.component("todo",{
template: '<div>\
<slot name="todo-tip"></slot>\
<ul>\
<slot name="todo-item"></slot>\
</ul>\
</div>'
})
Vue.component("todo-tip",{
props: ['title'],
template:'<div>{{title}}</div>'
})
Vue.component("todo-item",{
props: ['it'],
template: '<li>{{it}} <button>删除</button></li>'
})
var vm = new Vue({
el: "#app",
data: {
message: ['A','B','C','D','E','F','G'],
title: '迪迦羊肉串'
}
})
展示数据:
<div id="app">
<todo>
<todo-tip slot="todo-tip" :title="title"></todo-tip>
<todo-item slot="todo-item" :it="msg" v-for="(msg,index) in message" ></todo-item>
</todo>
</div>
2.为vm中绑定删除元素函数
var vm = new Vue({
...
methods: {
rmItem: function(dex) {
console.log("当前删除的是"+this.message[dex])
this.message.splice(dex,1)
}
}
})
3.将函数绑定到组件上
<todo-item v-on:myclick="rmItem(index)"></todo-item>
4.在组件中创建函数并且调用
template: '<li>{{it}} <button @click="todo_rm">删除</button></li>', //在button中绑定函数
methods: {
todo_rm: function(){
this.$emit('myclick') // 自定义函数调用
}
}
5.点击删除按钮
整体来说其实还是比较绕的,所以在写自定义事件之前,要理清楚思路,便会豁然开朗了~