當我們需要在操作組件后引起組件之外的元素發生變化時,就需要是這里的內容。比如:當選中書后,自動顯示您選中的書名。其中書籍列表是使用組件寫的。顯示選中書籍名是在組件之外。
在添加事件的時候需要注意一下事項:
1、在定義組件時`Vue.component(組件名,{props(參數),template(html代碼),methods(子組件中的事件),}`,
在子組件中正常調用該事件,但是在需要與父組件聯系時,需要在該事件中寫第2條的信息。
2、在需要出發事件的時候,調用`this.emit('事件的名稱',參數(可以是多個))
3、在使用這個組件的時候,綁定下事件,語法和之前綁定是一樣的,比如:@father-click="FatherClick",
@事件名稱=父組件中事件。
<!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>