vue3组件传值

102 阅读1分钟

父传子:props

在子组件传递需要传递的参数,子组件使用defineProps接收

//父组件
<template>
  <div class="box">
    <son :title="title"> </son>
    {{ title }}
  </div>
</template>
<script setup>
import son from "./son.vue";
const title = '我是父组件数据'
</script>
<style lang="scss" scoped>
.box {
  width: 600px;
  height: 600px;
  background-color: aquamarine;
}
</style>
//子组件
<template>
    <div class="box-son">
    我是子组件接收:{{title}}
    </div>
</template>
<script setup>
const props = defineProps(['title'])
</script>
<style scoped>
.box-son{
    width: 300px;
    height: 300px;
    background-color: pink;
}
</style>

子传父:使用$emit发射一个函数,父组件调用函数,接收子组件的传递的值

//子组件
<template>
    <div class="box-son">
        子组件:{{ name }}
    <button @click = hander>传给父组件</button>
    </div>
</template>
<script setup>
const name = '我是子组件的值'
const $emit = defineEmits(['chile'])
const hander = ()=>{
    $emit('chile',name)
}
</script>
<style scoped>
.box-son{
    width: 300px;
    height: 300px;
    background-color: pink;
}
</style>
//父组件
<template>
  <div class="box">
    <son @chile = hander> </son>
    {{name}}
  </div>
</template>
<script setup>
import {ref} from 'vue'
import son from "./son.vue";
const name = ref('')
const hander = (prop)=>{
  name.value = prop
  console.log(prop);
}

</script>
<style lang="scss" scoped>
.box {
  width: 600px;
  height: 600px;
  background-color: aquamarine;
}
</style>

兄弟传:mitt函数实现

  1. 在vue3 setup函数中,默认没有this,所以使用不了evenbus中央事件处理,但是我们可以使用mitt函数来实现兄弟传值,具体逻辑与evenbus差不多。
  2. 先创建bus.ts文件,npm下载mitt包,导入mitt函数,实例化mitt函数,导出实例化
//bus.ts文件
import mitt from 'mitt'
const $bus = mitt()
export default $bus
//兄弟a
<template>
    <div class="box-son">
        子组件1
        <button @click="hander">点击给兄弟传值</button>
    </div>
</template>
<script setup>
//导入$bus
import $bus from './bus'
const money = 10000
const hander =()=>{
    $bus.emit('brother',money)
}


</script>
<style scoped>
.box-son{
    width: 300px;
    height: 300px;
    background-color: pink;
}
</style>
//兄弟b
<template>
    <div class="box-son">
        子组件2:兄弟给的钱¥{{ match }}
    </div>
</template>
<script setup>
import { ref } from 'vue'
import $bus from './bus'
const match = ref()
//兄弟b接收使用$bus.on接收,它接收两个参数,第一个参数是事件名,第二个参数是回调函数,回调函数中接收兄弟a传过来的值
$bus.on('brother',(money)=>{
    match.value = money
})
</script>
<style scoped>
.box-son{
    width: 300px;
    height: 300px;
    background-color: pink;
}
</style>
//父组件
<template>
  <div class="box">
    <sona> </sona>
    <sonb></sonb>
  </div>
</template>
<script setup>
import {ref} from 'vue'
import sona from "./sona.vue";
import sonb from './sonb.vue';

</script>
<style lang="scss" scoped>
.box {
  width: 600px;
  height: 600px;
  background-color: aquamarine;
}
</style>