8.0、vue自定义事件内容分发

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值