父子组件通信

50 阅读1分钟

1.父传子

  • 父组件代码
<template>
  <div class="father">
    父组件
    <!-- 父传子 :count 绑定属性 -->
    <SonCom :count="count" msg="这是父组件的消息" ></SonCom>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import SonCom from './SonCom.vue';

const count = ref(100)

</script>

<style scoped>
.father {
  width: 40vw;
  height: 40vh;
  border: 1px solid lightblue;
}
</style>
  • 子组件代码
<template>
  <div class="son">
    <!-- 父传子传递下来的数据 在模板中可以直接使用 -->
    子组件 - {{ count }} - {{ msg }}
    <button @click="sonSend">子组件的按钮</button>
  </div>

</template>

<script setup>
// 父传子  defineProps接收
// 父传子传递下来的数据 如果要在script里使用 则需要使用一个变量来接收
const props = defineProps({
  msg: {
    type: String,
    default:'消息'
  },
  count: {
    type: Number,
    default:0
  }
})
console.log(props.msg); // 在script里使用
</script>

<style scoped>
.son {
  width: 25vw;
  height: 20vh;
  border: 1px solid rgb(40, 184, 100);
}
</style>

子传父
基本思想:

  • 1.父组件中给子组件标签通过@绑定事件

  • 2.子组件内部通过$emit方法触发事件

  • 父组件代码

<template>
  <div class="father">
    父组件
    <!-- 通过@绑定自定义事件 =后面携带一个父组件中的函数 -->
    <!-- @后面的是给子组件看的  =后面的函数 是父组件要调用的 -->
    <SonCom @getMsg="getMessage"></SonCom>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import SonCom from './SonCom.vue';

const getMessage = (msg) => {
  console.log(msg);
}

</script>

<style scoped>
.father {
  width: 40vw;
  height: 40vh;
  border: 1px solid lightblue;
}
</style>
  • 子组件代码
<template>
  <div class="son">
    <!-- 父传子传递下来的数据 在模板中可以直接使用 -->
    子组件 
    <button @click="sonSend">子组件的按钮</button>
  </div>

</template>

<script setup>
// 子传父 通过defineEmits编译宏函数 生成一个emit方法  等价于$emit
// defineEmits要求是个数组参数  要把当前组件触发所有的自定义事件全传到这里面来  这里面也就是放父组件@后面的名字
const emit = defineEmits(['getMsg'])
const sonSend = () => { 
  // 触发自定义事件getMsg 并且传递参数  这个参数会在父组件中的msg中当参数
  emit('getMsg','这是子传父') 
}

</script>

<style scoped>
.son {
  width: 25vw;
  height: 20vh;
  border: 1px solid rgb(40, 184, 100);
}
</style>