吉林建设厅网站深圳百度seo哪家好
自定义事件
通以上代码不难发现,数据项在Vue的实例中, 但删除操作要在组件中完成, 那么组件如何才能删除Vue实例中的数据呢?此时就涉及到参数传递与事件分发了, Vue为我们提供了自定义事件的功能很好的帮助我们解决了这个问题; 使用this.$emit(‘自定义事件名’, 参数) , 操作过程如下:
1-在vue的实例中增加了methods对象并定义了一个名为removeTodoltems的方法
2-修改todo-items待办内容组件的代码,增加一个删除按钮,并且绑定事件!
3-修改todo-items待办内容组件的HTML代码,增加一个自定义事件,比如叫remove,可以和组件的方法绑定,然后绑定到vue的方法!
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<div id="app"><todo><todo-title slot="todo-title" :title="title"></todo-title><todo-items slot="todo-items" v-for="(item,index) in todoItems":items="item" v-bind:index="index" v-on:remove="removeItems(index)" :key="index"></todo-items></todo></div><!--导入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.min.js"></script>
<script>//solt:插槽Vue.component("tudo",{template:'<div>\<slot name="todo-title"></slot>\<ul>\<slot name="todo-items"></slot>\</ul>\</div>'});Vue.component("todo-title",{props:['title'],template: '<div>{{title}}</div>'});Vue.component("todo-items",{props: ['items','index'],//只能绑定当前组件的方法template:'<li>{{index}}-----{{items}} <button @click="remove">删除</button></li>',methods: {remove: function (index) {//this.$emit自定义事件分发this.$emit('remove',index)}}});var vm = new Vue({el: "#app",data: {title: "书籍列表",todoItems:["Java","Python","C++"]},methods: {removeItems: function (index) {console.log("删除了"+this.todoItems[index]+"OK");this.todoItems.splice(index,1,"haha"); //一次删除一个元素}}})
</script>
</body>
</html>
对上一个代码进行修改,实现删除功能逻辑理解