vue非父子组件传值

tech2024-12-16  6

1.单独的事件中心管理组件间的通信

var eventHub = new Vue()

2.监听事件与销毁事件

eventHub.$on('add-todo',addTodo) eventHub.$off('add-todo')

举例: (1)事件中心(js文件)

import Vue from 'vue' const hub = new Vue() export default hub

(2)组件A

<template> <div> {{value2}} </div> </template> <script> import hub from '@/assets/js/broadcast' export default { name: 'brother', data () { return { value2: '123' } }, mounted () { hub.$on('tom-event', (val) => { this.value2 = val }) } } </script>

(3)组件B

<template> <div> <el-button @click="add">点击</el-button> </div> </template> <script> import hub from '@/assets/js/broadcast' export default { name: 'test', methods: { add () { hub.$emit('tom-event', '1234567') }, } </script>
最新回复(0)