8.0、vue自定义事件内容分发
如果想要删除数据就必须要操作vm对象里的data属性,但是在component里定义的函数并不能直接的访问vm对象里的data数据,所以我们得利用view视图层来获取vm对象里的data数据。
首先我们知道Vue是双向绑定:
视图层可以访问component层,component也能访问视图层。
视图层能访问vm层,vm层也能访问view视图层。
所以我们可以这么做,删除按钮绑定component层methods中remove()函数,然后用this.$emit('removes',index)再去绑定view层的方法v-on:removes="removeitems(index)",view层的方法再去调用vm层的函数removeitems(index)根据index来删除data展示在前端的数据。
在vm层的methods中用到了splice(index,1)方法:index表示从这个下标的元素开始,1表示只删除当前index这个索引的元素。如果改成2表示从当前index索引开始,删除当前元素以及当前元素的下一个元素。
具体代码如下所示:
<!DOCTYPE html><html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"><title>vuetest7</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
</head>
<body>
<div id="div1">
<todo>
<booktitle slot="title" v-bind:title="title"></booktitle>
<booksname slot="booksname" v-for="(item,index) in items"
v-bind:booksname="item.booksname" v-on:removes="removeitems(index)"></booksname>
</todo>
</div>
<script>
Vue.component("todo",{
template: '<div>' +
'<slot name="title"></slot>' +
'<ul>' +
'<slot name="booksname"></slot>'+
'</ul>'+'</div>'
});
Vue.component("booktitle",{
props: ['title'],
template: '<div>{{title}}</div>'
});
Vue.component("booksname",{
props: ['booksname'],
template: '<div> {{booksname}} <button v-on:click="remove">删除</button></div>',
methods: {
remove:function () {
this.$emit('removes');
}
}
});
var vm = new Vue({
el: "#div1",
data: {
title: "java全栈工程师必修课!",
items: [
{"booksname":"java"},
{"booksname":"css"},
{"booksname":"js"}
]
},
methods: {
removeitems:function (index) {
this.items.splice(index,1);
}
}
});
</script>
</body>
</html>