web123456

Vue3 component passes value (using setup syntax sugar writing)

1. Father passes on to sondefineProps

1.1 fatherComponentsCode: (pass data)

// Pass the value:
<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 sonComponent code: (receive data)

<script setup>
// There is no need to introduce defineProps function, you can use it directly
defineProps({
   num: {
      type: Number,
      default: 6
   }
});
<script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2. The son passes on to the fatherdefineEmits

2.1 sonComponent code: (pass data)

<script setup>
let emit = defineEmits(['sendMsg']); 
// clickEvent is a callback function for click event
let clickEvent = function(){
  emit('sendMsg','This is the data passed to the parent component');
}
<script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2.2 fatherComponent code: (receive data)

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

<script setup>
let receiveEvent = function(event){
  // event is the data transmitted from the subcomponent
  console.log(event);
}
<script>

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