Vue--子组件之间相互调用及传值
父组件
创建子组件公用的空vue
变量,为pubVue
,并传给需要互相传参/互相调用方法的两个子组件
<template> <div> <btn-tools :pubVue="pubVue" /> <table-list :pubVue="pubVue" /> </div> </template> <script> // 组件引用 import TableList from './components/table-list' import BtnTools from './components/btn-tools' import Vue from 'vue' export default { name: 'PDmaterialList', components: { TableList, BtnTools }, data() { return { pubVue: new Vue() } } } </script>
子组件一 $emit发送事件
<template> <div> <el-button icon="el-icon-search" type="primary" @click="test" /> </div> </template> <script> export default { props: { pubVue: { type: Object } }, methods: { test() { console.log('方法派发') this.pubVue.$emit('YOUR_EVENT_NAME', { name: '张三' }) } } } </script>
子组件二 $on监听事件
<template> <div> <div>子组件二</div> </div> </template> <script> export default { props: { pubVue: { type: Object } }, mounted() { this.pubVue.$on('YOUR_EVENT_NAME', data => { console.log('方法监听', data) }) } } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步