「后端小伙伴来学前端了」Vue中利用全局事件总线改造 TodoList 案例
前言
上上篇寫了:👉Vue中利用Props實現TodoList案例
上篇寫了:👉Vue中全局事件總線的概念及基本使用
這篇就打算用全局事件總線來改造一下之前寫的TodoList案例,一天學習一點,我們一起進步沖。
一、案例效果
需要實現的東西,和之前是一樣的,只是我們換成用全局事件總線來進行組件之間的通信。
二、分析為什么要換成全局事件總線
為什么需要換成全局事件總線勒?我們拿Props也能夠實現這些功能啊,可以是可以實現,但是我們看看之前有哪些問題的存在。
我們之前在App組件中套入了一個List組件,然后在List組件套了一個Item組件,數據定義在App組件,就意味著我們要實現祖孫組件之間通信。
props實現如下:
一直傳遞到Item組件中才使用
作為咱們程序員來說,在一個組件中,寫了但是又完全沒有使用的東西,就是多余的哈。
不過尤雨溪大佬已經替我們懶完了,就有了這些全局事件總線啊,還有Vuex這種生態,來方便我們進行組件通信。
使用全局事件總線就可以解決這個問題,更方便實現祖孫組件之間通信。
三、全局事件總線實現TodoList
我們著重于實現app組件和Item組件之間的通信,也就是祖孫組件之間的通信哈。
另外兄弟組件也是一樣的實現方法哈,實現起來,再也不用像props那樣多層傳遞了,也不用再借助中間層拉,直接綁定即可以通信拉。
祖孫組件之間通信
App組件:
<template><div class="todo-container"><!-- header模塊 --><TodoHeader/><!-- main 模塊 --><TodoList :todos="todos"/><!-- 主要的內容模塊 --><TodoFooter :todos="todos" :clearDoneTodos="clearDoneTodos" :checkAllTodos="checkAllTodos" /><!-- footer模塊 --></div> </template> <script> import TodoHeader from './components/MyTodoHeader' import TodoList from './components/MyTodoList' import TodoFooter from './components/MyTodoFooter' export default {components: {TodoHeader,TodoList,TodoFooter},data () {return {todos: [{ id: '001', title: '吃飯', done: true },{ id: '002', title: '睡覺', done: false },{ id: '003', title: '敲代碼', done: true }]}},methods: {// 回車增加一個todoaddTodo (todo) {this.todos.unshift(todo)},// 判斷勾選不勾選checkTodo (id) {this.todos.forEach((todo) => {if (todo.id === id) todo.done = !todo.done})},// 刪除一個tododeleteTodo (id) {this.todos = this.todos.filter(todo => todo.id !== id)},// 全選全不選checkAllTodos (done) {this.todos.forEach((todo) => { todo.done = done })},// 清除所有已完成的任務clearDoneTodos () {this.todos = this.todos.filter(todo => !todo.done)}},// 在加載完成后就進行全局總線的綁定mounted () {this.$bus.$on('addTodo', this.addTodo)this.$bus.$on('checkTodo', this.checkTodo)this.$bus.$on('deleteTodo', this.deleteTodo)},// 養成習慣 在組件銷毀的時候,將事件進行解綁beforeDestroy () {this.$bus.$off('addTodo')this.$bus.$off('checkTodo')this.$bus.$off('deleteTodo')}} </script> <style> *{ margin: 0 0; padding: 0 0; } .todo-container{margin:0 auto;margin-top: 10px;width: 500px;height: 500px;background-color: #CCC;border: 1px solid #ddd;border-radius:8px; } </style>List組件:
<template> <ul class="todo-main"><TodoItem v-for="(todo, index) in todos" :key="index" :todo="todo" /></ul> </template> <script> import TodoItem from './MyTodoItem' export default {components: {TodoItem},props: {todos: Array},methods: {} } </script> <style scoped> /*main*/ .todo-main {margin-top: 10px;margin-left: 0px;border: 1px solid #ddd;border-radius: 2px;padding: 0px; }.todo-empty {height: 40px;line-height: 40px;border: 1px solid #ddd;border-radius: 2px;padding-left: 5px;margin-top: 10px; }/*item*/ li {list-style: none;height: 36px;line-height: 36px;padding: 0 5px;border-bottom: 1px solid #ddd; }li label {float: left;cursor: pointer; }li label li input {vertical-align: middle;margin-right: 6px;position: relative;top: -1px; }li button {float: right;display: none;margin-top: 3px; }li:before {content: initial; }li:last-child {border-bottom: none; } </style>MyTodoItem組件
<template><li @mouseenter="handleEnter(true)" @mouseleave="handleEnter(false)" :style="{background: bgColor}"><label><input type="checkbox" :checked="todo.done" @click="handlerCheck(todo.id)" /><span>{{todo.title}}</span></label><button class="btn btn-danger" style="display:none" v-show="isShow" @click="handlerDeleteItem(todo.id)">刪除</button></li> </template><script> export default {props: {todo: Object},data () {return {bgColor: 'white',isShow: false}},methods: {handleEnter (isEnter) {if (isEnter) {this.bgColor = '#aaa'this.isShow = true} else {this.bgColor = 'white'this.isShow = false}},// 修改勾選狀態handlerCheck (id) {console.log(id)// this.checkTodo(id)// 使用全局事件 總線 不再需要麻煩中間組件 list 就可以做到直接通信this.$bus.$emit('checkTodo', id)},handlerDeleteItem (id) {if (window.confirm('確定刪除嗎')) {// this.deleteTodo(id)this.$bus.$emit('deleteTodo', id)}}} } </script>這樣就省去了MyList組件去做中間層。另外代碼及結構也會顯得更加的清晰。
兄弟組件之間通信
現在我們的需求是需要在Footer組件中點擊修改按鈕,然后能夠做到修改List組件下的Item組件的值(寧在春的這個值)
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-yAte2u8c-1637166284627)(C:\Users\ASUS\Desktop\寧在春的學習筆記\前端系列\前端學習筆記\09Vue中利用全局總線實現TodoList案例.assets\image-20211118001654427.png)]
item組件
<template><li@mouseenter="handleEnter(true)"@mouseleave="handleEnter(false)":style="{ background: bgColor }"><label><inputtype="checkbox":checked="todo.done"@click="handlerCheck(todo.id)"/><span>{{ todo.title }}</span>//這里就是展示的數據<span>{{ msg }}</span></label><buttonclass="btn btn-danger"style="display: none"v-show="isShow"@click="handlerDeleteItem(todo.id)">刪除</button></li> </template><script> export default {props: {todo: Object},data () {return {bgColor: 'white',isShow: false,msg: ' 寧在春'}},methods: {handleEnter (isEnter) {if (isEnter) {this.bgColor = '#aaa'this.isShow = true} else {this.bgColor = 'white'this.isShow = false}},// 修改勾選狀態handlerCheck (id) {console.log(id)// this.checkTodo(id)// 使用全局事件 總線 不再需要麻煩中間組件 list 就可以做到直接通信this.$bus.$emit('checkTodo', id)},handlerDeleteItem (id) {if (window.confirm('確定刪除嗎')) {// this.deleteTodo(id)this.$bus.$emit('deleteTodo', id)}},updateMsg () {this.msg = '大家好啊,我叫寧在春'}},mounted () {//綁定事件 后面跟著的this.updateMsg 是自己定義在 methods 中的方法this.$bus.$on('updateMsg', this.updateMsg)},// 養成習慣 在組件銷毀的時候,將事件進行解綁beforeDestroy () {this.$bus.$off('updateMsg')} } </script> <template><div class="todo-footer" v-show="total"><label><!-- // 第一種方式:通過dom元素來判斷有沒有進行勾選 不是最佳方式 --><!-- <input type="checkbox" :checked="isAllCheck" @click="checkAll" /> --><!-- 第二種方式: 通過綁定計算屬性來進行展示 --><input type="checkbox" v-model="isAllCheck" /></label><span>已完成{{ doneTotal }}<span> / 全部{{ todos.length }} </span></span><buttonclass="btn btn-danger"@click="deleteDoneAll">清除已完成任務</button>//點擊修改<button @click="updateMessag">點擊修改</button></div> </template><script> export default {props: {todos: Array,clearDoneTodos: Function,checkAllTodos: Function},computed: {total () {return this.todos.length},doneTotal () {return this.todos.reduce((preTotal, todo) => preTotal + (todo.done ? 1 : 0), 0)},isAllCheck: {get () {return this.doneTotal === this.todos.length && this.doneTotal > 0},// 通過計算屬性來判斷是否全選或全不選set (checked) {this.checkAllTodos(checked)}}},methods: {deleteDoneAll () {this.clearDoneTodos()},updateMessag () {//執行之前綁定的回調函數this.$bus.$emit('updateMsg')}} } </script>實現效果
四、源碼
gitee
github
后語
大家一起加油!!!如若文章中有不足之處,請大家及時指出,在此鄭重感謝。
紙上得來終覺淺,絕知此事要躬行。
大家好,我是博主寧在春:主頁
一名喜歡文藝卻踏上編程這條道路的小青年。
希望:我們,待別日相見時,都已有所成。
總結
以上是生活随笔為你收集整理的「后端小伙伴来学前端了」Vue中利用全局事件总线改造 TodoList 案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「后端小伙伴来学前端了」Vue中利用全局
- 下一篇: 「后端小伙伴来学前端了」Vue中为什么直