vue3.2 script setup 父子组件传值
父组件代码
<!-- 父组件代码 -->
<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传递给参数给父组件