<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <title>Vue组件中自定义事件</title> </head> <body> <div id="app"> <child-template v-for="book in books" :book="book" @father-click="FatherClick"></child-template> <p>你选中了:{{checkbooks}}</p> </div> <script> Vue.component("child-template", { props: [‘book‘], template: ` <div> <label>{{book.title}}</label> <input type="checkbox" @click="onCheck" > </div> `, methods: { onCheck() { // 将子组件与父组件联合起来 this.$emit(‘father-click‘, this.book) } }, }) new Vue({ el: "#app", data: { books: [{ title: ‘水浒传‘, }, { title: ‘三国演义‘, }, { title: ‘西游记‘, }, { title: ‘红楼梦‘, }, ], checkbooks: [] }, methods: { ‘FatherClick‘(bookName) { // indexOf:获取某个元素在数组中的位置,如果返回值为非负数,那么就是存在,就是下标 // 否则,代表这个元素在数组中不存在 let booknameIndex = this.checkbooks.indexOf(bookName.title) if (booknameIndex >= 0) { this.checkbooks.splice(booknameIndex, 1) } else { this.checkbooks.push(bookName.title) } } } }) </script> </body> </html>
原文:https://www.cnblogs.com/xshan/p/12341906.html