Vue 自定义事件内容分发

简单例子

假设在前面的代码加入一个删除按钮,但是由于数据是来自vue的。如何去实现同步?

vue通过自定义事件解决这个问题,语法为this.$emit('自定义事件名',参数)
代码:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <todo>
        <todo-title slot="todo-title" v-bind:temptitle="title" ></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:tempitem="item" :index="index" v-on:remove="removeItems(index)"></todo-items>
    </todo>

</div>



<script src="js/vue.js"></script>
<script>
    'use strict'
    Vue.component('todo',{
        template: `
        <div>\
            <slot name="todo-title"></slot>
            <ul>
               <slot name="todo-items"></slot>
            </ul>
        </div>
        `
    });

    Vue.component('todo-title',{
        props:['temptitle'],
        template: `<div>{{temptitle}}</div>`
    });
    Vue.component('todo-items',{
        props:['tempitem','index'],
        template:'<li>{{index}} {{tempitem}} <button @click="remove">删除</button></li>',
        methods:{
            remove:function (index) {
                this.$emit('remove',index);
            }
        }
    });
    var vm=new Vue({
        el:"#app",
        data:{
            title: "学习的东西",
            todoItems: ['Java','Linux','C++']
        },
        methods:{
            removeItems:function (index) {
                //通过splice函数实现删除数组下标
                return this.todoItems.splice(index,1);
            }
        }
    });
</script>
</body>
</html>
posted @ 2021-05-09 11:35  一个经常掉线的人  阅读(109)  评论(0)    收藏  举报