Vue3 父子组件传参数script setup
父组件father.vue
<template>
<div class="w-4/5 ml-auto mr-auto">
<h1 class="text-4xl font-bold mt-5 mb-5">父组件</h1>
<div class="text-xl mt-5 mb-5">父组件的值 num:{{ num }}</div>
<div class="text-xl mt-5 mb-5">
<n-button type="info" @click="fatherClick">调用子组件的方法</n-button>
</div>
<hr class="bg-gray-200 mb-2 border-0 h-1" />
<children ref="childrenRef" :num="num" @changeData="changeData"></children>
</div>
</template>
<script setup>
import { ref } from 'vue';
import children from './children.vue';
const childrenRef = ref(null);
const num = ref(1);
function fatherClick() {
childrenRef.value.changeNum();
}
function changeData() {
num.value++;
}
</script>
子组件children.vue
<template>
<div class="text-3xl mt-5 text-red-600">子组件</div>
<div class="text-xl mt-5">子组件的值 childrenNum:{{ childrenNum }}</div>
<div class="text-xl mt-5">
<n-button type="primary" @click="parentChangeNum">调用父组件的方法</n-button>
</div>
</template>
<script setup>
import { ref, defineProps } from 'vue';
const props = defineProps({
num: {
type: Number,
default: 0,
},
});
const childrenNum = ref(props.num);
const emits = defineEmits(['changeData']);
function changeNum() {
childrenNum.value++;
}
function parentChangeNum() {
emits('changeData', childrenNum.value);
}
defineExpose({
changeNum,
});
</script>