vue3怎么兄弟组件传值
时间: 2023-12-05 19:40:57 浏览: 37
Vue3中兄弟组件传值有多种方法,其中两种常用的方法如下:
1.使用事件总线(Event Bus)进行传值,具体步骤如下:
在父组件中创建一个事件总线实例,并在需要传值的地方触发事件,将数据作为参数传递给事件;在子组件中监听该事件,并在回调函数中获取传递的数据。示例代码如下:
// 父组件
<template>
<div>
<h1>我是父组件</h1>
<button @click="sendMsg">发送消息给子组件</button>
</div>
</template>
<script>
import { ref } from 'vue'
import mitt from 'mitt'
export default {
setup() {
const emitter = mitt()
const msg = ref('父组件的消息')
const sendMsg = () => {
emitter.emit('getMsg', msg.value)
}
return {
emitter,
sendMsg
}
}
}
</script>
// 子组件
<template>
<div>
<h1>我是子组件</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
import mitt from 'mitt'
export default {
setup() {
const emitter = mitt()
const msg = ref('')
onMounted(() => {
emitter.on('getMsg', (data) => {
msg.value = data
})
})
return {
emitter,
msg
}
}
}
</script>
2.使用插件mitt进行传值,具体步骤如下:
在父组件和子组件中都引入mitt插件,并在父组件中创建一个mitt实例,然后在需要传值的地方调用emit方法,将数据作为参数传递给子组件;在子组件中通过props接收父组件传递的数据。示例代码如下:
// 父组件
<template>
<div>
<h1>我是父组件</h1>
<button @click="sendMsg">发送消息给子组件</button>
</div>
</template>
<script>
import { ref } from 'vue'
import mitt from 'mitt'
export default {
setup() {
const emitter = mitt()
const msg = ref('父组件的消息')
const sendMsg = () => {
emitter.emit('getMsg', msg.value)
}
return {
emitter,
sendMsg
}
}
}
</script>
// 子组件
<template>
<div>
<h1>我是子组件</h1>
<p>{{ msg }}</p>
</div>
</template>
<script>
import { ref, onMounted, reactive } from 'vue'
import mitt from 'mitt'
export default {
props: {
msg: {
type: String,
default: ''
}
},
setup(props) {
const emitter = mitt()
onMounted(() => {
emitter.on('getMsg', (data) => {
props.msg = data
})
})
return {
emitter
}
}
}
</script>
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)