一、父子组件传值props

A、子组件

  1. <template>
  2. <div><button>{{props.count}}</button></div>
  3. </template>
  4. <script setup>
  5. import {defineProps} from 'vue'
  6. const props = defineProps({
  7. count:{
  8. type:Number,
  9. default:0
  10. }
  11. })
  12. </script>

B、父组件

  1. <template>
  2. <CountItem :count="count"></CountItem>
  3. </template>
  4. <script setup>
  5. import { ref } from '@vue/reactivity'
  6. import CountItem from './Children/CountItem.vue'
  7. const count = ref(0)
  8. </script>

二、子组件给父组件传值emit

A、子组件

  1. <template>
  2. <div><button @click="handleChange">{{props.count}}</button></div>
  3. </template>
  4. <script setup>
  5. import {defineProps,defineEmits} from 'vue'
  6. /* 定义props属性 */
  7. const props = defineProps({
  8. count:{
  9. type:Number,
  10. default:0
  11. }
  12. })
  13. /* 定义emit */
  14. const emit = defineEmits({
  15. "onChangeCount":null
  16. })
  17. function handleChange(){
  18. emit("onChangeCount")
  19. }
  20. </script>

B、父组件

  1. <template>
  2. <CountItem :count="count" @onChangeCount="handleCount"></CountItem>
  3. </template>
  4. <script setup>
  5. import { ref } from '@vue/reactivity'
  6. import CountItem from './Children/CountItem.vue'
  7. const count = ref(0)
  8. function handleCount(){
  9. count.value++
  10. }
  11. </script>