vue入门笔记-10-自定义事件内容分发


自定义事件分发.

使用 this.$emit进行自定义事件的分发:通过这个可以使用组件调用 vm对象的方法

template: '<li> <button @click="remove">删除</button></li>'

  • 组件内的模板,其中 @click="remove" 自定义事件,事件名叫remove

组件中的方法methods:{ remove:function (index) { this.$emit('remove',index); } }

  • this.$emit('remove',index);

  • remove:自定义事件名

  • index:vm传递来的参数

@remove="removeItem(index)"

  • 自定义事件绑定vm对象方法

vm对象中对应的方法methods: { removeItem: function (index) { this.items.splice(index,1);//删除一个元素 按索引 } }

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义事件分发</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <todo>
        <todo-title slot="slot1" :title="title"></todo-title>
        <todo-item slot="slot2" v-for="(item,index) in items" :item="item" :index="index" @remove="removeItem(index)" :key="index"></todo-item>
    </todo>
</div>
<script>
    Vue.component('todo',{
        template: '<div>' +
            '<slot name="slot1"></slot>'+
            '<ul>' +
            '<slot name="slot2"></slot>' +
            '</ul>' +
            '</div>'
    });

    Vue.component('todo-title',{
        props:['title'],
        template: '<p>{{title}}</p>'
    });

    //加一个删除按钮 并且绑定自定义事件
    Vue.component('todo-item',{
        props:['item','index'],
        template: '<li>{{item}} &nbsp;&nbsp;<button @click="remove">删除</button></li>',
        methods:{
            remove:function (index) {
                this.$emit('remove',index);
            }
        }
    });



   var vm = new Vue({
       el:"#app",
       data:{
           title:"前后端学习",
           items:['<h1>java</h1>','vue','liuyou']
       },
       methods: {
           removeItem: function (index) {
               this.items.splice(index,1);//删除一个元素 按索引
           }
       }
    });


</script>
</body>
</html>

文章作者: liuminkai
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 liuminkai !
评论
 上一篇
vue入门笔记-11-入门小结 vue入门笔记-11-入门小结
Vue入门小结.核心:数据驱动,组件化 优点:借鉴了AngularJS的模块化,和React的虚拟DOM,虚拟DOM就是把DOM操作放到内存中执行; 常用的属性: v-if v-else-if v-else v-for v-on(简写 @
2020-08-10
下一篇 
vue入门笔记-09-插槽slot vue入门笔记-09-插槽slot
插槽slot.我的理解,可以把多个组件(甚至可以是普通标签,文本,模板数据)通过插槽添加到另一个组件中,但是这些要看插槽是否有name属性 这个组件,也可看做是个自定义标签 一个组件中,没有slot,就不能解析其标签内部的所有字符
2020-08-09
  目录