vue3 setup语法糖 父子组件互相传递

414 阅读1分钟

defineEmits defineProps 的使用

child组件

definePropsdefineEmits 只能在setup 语法糖下使用,不在该下面使用会报错

definePropsdefineEmits 分别用来声明propsemit ,在setup下可以直接使用

详细可以看下官方文档

<template>

  <div>

    我是child组件

  </div>

  <button @click="handleCLick">点我传递事件</button>

  <br/>

  <h2>从App组件传递过来的数据:{{sum}}</h2>

</template>

<script setup>

import { reactive } from 'vue'

const data = reactive({

  name: 'tom',

  age: 18

})

const emit = defineEmits(['handleEemit'])

defineProps({

  sum:{

    type:Number,

  }

})


const handleCLick = () => {

  emit('handleEemit',data)

}

</script>

App组件

<template>

  <div>

    我是App组件

  </div>

  <h2>从Child组件接收到的数据:{{childData.data}}</h2>

  <br/>

  <Child @handleEemit="handleEemit" :sum="sum"></Child>

</template>


<script setup>

  import { ref ,reactive} from 'vue'

  import Child from './view/child.vue'

  let sum = ref(0)

  let childData = reactive({data:''})

  const handleEemit =(e) => {

    console.log('我接受到数据了',e)

    childData.data = {...e}

    console.log(childData)

  }

</script>

<style>

  #app {

    text-align: center;

  }

</style>

打印结果

166bc1dcad14deb29b89ab1cfd562fe.png