本文介紹使用發布訂閱的方式進行vue組件間的通信
我認為這種方式比較自由, 不存在組件間的關系問題
1. 首先安裝pubsub-js
npm install --save pubsub-js
2. 訂閱方組件
import PubSub from 'pubsub-js'
mounted(){ // 執行異常代碼 // 訂閱消息 PubSub.subscribe('deleteTodo',(msg,index)=>{ this.deleteTodo(index) // 調用deleteTodo方法執行真正的業務邏輯 }); },
3. 發布方組件
<script> import PubSub from 'pubsub-js' export default{ methods: { handlerEnter(isEnter){ if (isEnter) { this.bgColor = 'gray'; this.isShow = true; } else { this.bgColor = 'white'; this.isShow = false; } }, deleteItem(){ // 表示從this對象中取出todo,index,deleteTodo三個對象 const {todo, index, deleteTodo} = this if (window.confirm(`確認刪除${todo.title}嗎?`)) { // 發布消息 PubSub.publish('deleteTodo', index); //deleteTodo一定要與訂閱方名稱一樣,index是通信的具體數據 } } } } </script>