一、父组件代码
javascript
//app.vue
<template>
<!-- 静态字符串传参不要加 : ;监听子组件抛出的click事件 -->
<HelloWorld btnText="按钮文本" bbt="测试参数" @click="targetPath" />
</template>
<script setup lang="ts" name="HelloWorld">
import HelloWorld from './components/HelloWorld.vue'
function targetPath() {
console.log('父组件收到按钮点击')
}
</script>
<style scoped>
</style>
二、子组件代码
javascript
<template>
<div class="nav-btn-right" @click="handleClick">
{{ btnText }}
</div>
</template>
<script setup lang="ts">
// ✅ 正确 defineProps 写法
const props = defineProps<{
btnText: string
bbt?: string // 可选参数
}>()
// 如果需要通知父组件,定义emit
const emit = defineEmits(['click'])
const handleClick = () => {
console.log('点击了按钮,文本:', props.btnText)
// 方式1:子组件内部完成逻辑
// 方式2:向外派发事件交给父组件处理
emit('click')
}
</script>
<style scoped>
.nav-btn-right {
padding: 8px 18px;
cursor: pointer;
user-select: none;
background-color: #165DFF;
color: #fff;
border-radius: 6px;
transition: all 0.2s ease;
font-size: 14px;
}
.nav-btn-right:hover {
background-color: #0E4BDB;
}
.nav-btn-right:active {
background-color: #0C42C2;
transform: scale(0.97);
}
</style>