vuejs3.0 从入门到精通——组件传值方法——兄弟组件之间的传值

兄弟组件之间的传值

一、第一种方案

A组件-->父组件-->B组件
 

 

1.1、A组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
    <div>
        <h1>A组件</h1>
        <button @click="changeA">按钮</button>
    </div>
</template>
 
<script setup lang='ts'>
import { ref } from 'vue'
let str = ref('我是A组件的数据');
 
const emit = defineEmits(['fn'])
const changeA = () => {
    emit('fn', str)
}
</script>

1.2、父组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
    <div>
        <A @fn='changeFn'></A>
        <B :str='str'></B>
    </div>
</template>
 
<script setup lang='ts'>
import A from './A.vue'
import B from './B.vue'
import { ref } from 'vue'
 
let str = ref('')
const changeFn = (strVal: string) => {
    console.log(strVal)
    str.value = strVal
}
</script>  

1.3、B组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
    <div>
        <h1>B组件</h1>
        {{ str }}
    </div>
</template>
 
<script setup lang='ts'>
 
const props = defineProps({
    str: {
        type: String,
        default: 'hello, 这是B组件数据'
 
    }
});
console.log(props.str)
</script>

二、第二种方案

2.1、组件安装

    1. npm install mitt -S
    2. mkdir -pv VITE-PROJECT/src/plugin/Bus.js
    3. echo "
      import mitt from 'mitt';
      const emitter = mitt();
      export default emitter;
      " >> VITE-PROJECT/src/plugin/Bus.js

2.2、A组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!--子组件: A 组件-->
 
<template>
    <div>
        <h1>A组件</h1>
        <button @click="changeA">按钮</button>
        <hr>
 
    </div>
</template>
 
<script setup lang='ts'>
import { ref } from 'vue'
import emitter from '@/plugin/Bus.ts'
 
let str = ref('我是A组件的数据');
 
const changeA = () => {
    emitter.emit('Fn', str)
}
</script> 

2.3、B组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!--子组件: B 组件-->
 
<template>
    <div>
        <h1>B组件</h1>
        {{ s }}
    </div>
</template>
 
<script setup lang='ts'>
import emitter from '@/plugin/Bus.ts'
import { onBeforeMount, ref } from 'vue'
 
let s = ref<unknown>(null);
 
onBeforeMount(() => {
    emitter.on('Fn', (e: unknown) => {
        s.value = e;
 
    })
})
</script>
posted @   左扬  阅读(378)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
levels of contents
点击右上角即可分享
微信分享提示