Vue的父子兄弟之间的传值

非总线机制

父传子

//父组件
<template>
<div>我是父组件</div>
<ZJA :li_a="li_a" :abc="abc" :hanshu="hanshu"></ZJA>
</template>

<script setup>
import { ref } from 'vue'
import ZJA from './component/zujian-a.vue'

const li_a = ref('dasd')
const abc = '我是父组件传来的'
const hanshu = () => {
console.log('顶顶顶顶')
}
</script>
//子组件
<template>
<div>
<div>{{ props.li_a }}</div>
<div>{{ props.abc }}</div>
<button @click="hanshu">调用父组件函数</button>
</div>
</template>

<script setup>
import { defineProps } from 'vue'

// 这是一种调用的方法,但要声明
// const props = defineProps({
// li_a: String,
// abc: String,
// hanshu: Function
// })

// 这一种直接使用
const props = defineProps([
'li_a',
'abc',
'hanshu'
])
</script>

子传父

子组件
<template>
<button @click="sendValueToParent">传值给父组件</button>
</template>

<script setup>
import { defineEmits, onMounted } from 'vue';

// 声明自定义事件
const emits = defineEmits(['childEvent']);

// 点击方法传函数和值
const sendValueToParent = ()=>{
const valueToSend = ()=>{
console.log("哈哈哈哈哈哈哈啊")
};
const h = '阿三大苏打撒旦'
emits('childEvent', valueToSend, h);
}

//生命周期传值
onMounted(() => {
const valueToSenda = '这是非按钮子组件传给父组件的值';
emits('childEventa', valueToSenda);
});

</script>
父组件
<template>
<div>我是父组件</div>

<p>从子组件接收到的值:{{ receivedValue }}</p>
<ZJB @childEvent="handleChildEvent" />

<p>不是从按钮子组件接收到的值:{{ receivedValuea }}</p>
<ZJB @childEventa="handleChildEventa" />

</template>

<script setup>
import { ref } from 'vue'
import ZJB from './component/zujian-b.vue'

//存储子组件传过来的值
const receivedValue = ref('');

// 点击方法获得子组件传过来的东西
const handleChildEvent = (valueToSend,h)=>{
receivedValue.value = h
valueToSend();//子组件传过来的函数
}

//存储子组件传过来的值
const receivedValuea = ref('');
// 生命周期方法获得子组件传过来的东西
function handleChildEventa(valueReceived) {
receivedValuea.value = valueReceived;
}

</script>

子传子的话可以先子传父在父传子

总线机制

其实和上面的很像的,只是要多一个js文件。

结构为
image-20240503142852677

js文件怎么写

dataStore.vue
文件的内容

import mitt from 'mitt';
// 创建一个响应式变量来存储需要传递的数据

// 创建事件总线
const eventBus = mitt();

const Father = mitt();

export { eventBus, Father }; // 导出 sharedData 变量和 eventBus 对象

每个组件文件都要引入

import { eventBus, Father } from './component/dataStore';

然后就是传值

import { eventBus, Father } from './component/dataStore';

这里一定要引入Father哈

const Parent = () => {
const dataToSend = '急急急急急急急急急急急急就';
Father.emit('fatherData', dataToSend);
};

和上面一样的,也可以传函数。

const Parent = () => {
const asdasd = ()=>{
console.log("萨达萨达萨达萨达撒旦撒旦")
}
Father.emit('fatherData', asdasd);
};

如果这个函数在外面也没关系,一样的方法进行传值

const asdasd = ()=>{
console.log("萨达萨达萨达萨达撒旦撒旦")
}

const Parent = () => {
asdasd()
Father.emit('fatherData', asdasd);
};

然后就是要接收的组件了

onMounted(()=>	{
    Father.on('fatherData',	(asdasd)	=>	{
            asdasd();
        });
});
这个一般放在一个生命周期函数中。自动接收嘛,或者其他的也行。

总结一下,非总线的子传父和总线机制比较相识,非总的父传子则最为简单。