父組件代碼
<!-- 父組件代碼 -->
<template>
<div id="nav">
<AboutVue :value="parentValue" @add="onParentClick" />
<br />
<button @click.stop="onParentClick()">父組件按鈕</button>
</div>
</template>
<script setup>
/**
* 引入必要的模塊
*/
import { ref } from 'vue'
import AboutVue from './views/About.vue'
/**
* 定義數據
*/
const parentValue = ref(0)
/**
* 定義方法
*/
function onParentClick (childValue) {
childValue ? (parentValue.value += childValue) : parentValue.value++
}
</script>
<style scoped>
#nav {
text-align: center;
}
</style>
子組件代碼
<!-- 子組件代碼 -->
<template>
<div class="about">
<h1>{{ props.value }}</h1>
<button @click="onChildClick">子組件按鈕</button>
</div>
</template>
<script setup>
/**
* 引入必要的模塊
*/
import { defineProps, defineEmits } from 'vue'
/**
* 定義數據
*/
const props = defineProps({ value: { type: Number } })
const emit = defineEmits(['add'])
/**
* 定義方法
*/
function onChildClick () {
emit('add', 2)
}
</script>
vue3.2 setup 語法糖中:子組件使用 defineProps接收props , 使用 defineEmits傳遞給參數給父組件