Vue3组件传值(使用setup语法糖写法)

时间:2025-04-08 08:20:04

1. 父传子defineProps

1.1 组件代码:(传递数据)

// 传递值:
<Child :num="n"></Child>

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

const n = ref(3);
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

1.2 组件代码:(接收数据)

<script setup>
// 不需要引入defineProps函数,可以直接使用
defineProps({
   num: {
      type: Number,
      default: 6
   }
});
<script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2. 子传父defineEmits

2.1 组件代码:(传递数据)

<script setup>
let emit = defineEmits(['sendMsg']); 
// clickEvent是一个点击事件的回调函数
let clickEvent = function(){
  emit('sendMsg','这是子组件传给父组件的数据');
}
<script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.2 组件代码:(接收数据)

<Child @sendMsg='receiveEvent'></Child>

<script setup>
let receiveEvent = function(event){
  // event就是子组件传过来的数据
  console.log(event);
}
<script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9