Vue父组件访问子组件的方法

非得搞这么复杂? …

const countdownButtonRef = ref<InstanceType<typeof countDownButton>
| null>(null)</InstanceType<typeof
>

子组件

<template>
<n-button :style="props.style" style="padding: 0" @click="onPress">
<div
:style="`color: ${
seconds == 0 || seconds == props.totalSeconds ? '#333' : '#999'
}`"
>
{{
seconds == 0
? "获取验证码"
: seconds == props.totalSeconds
? "重新获取"
: `重新获取(${props.totalSeconds - seconds}s)`
}}
</div>
</n-button>
</template>

<script lang="ts" setup>
const props = defineProps(["show", "totalSeconds", "style"]);
const emits = defineEmits(["onClose", "onPress"]);
const seconds = ref(0);
let timer = 0;

const start = () => {
seconds.value = 1;
timer && clearInterval(timer);
timer = setInterval(() => {
seconds.value++;
if (seconds.value == props.totalSeconds) {
clearInterval(timer);
}
}, 1000);
};

const onPress = () => {
if (seconds.value == 0 || seconds.value == props.totalSeconds) {
// start()
emits("onPress");
} else {
}
};

defineExpose({ start });
</script>

<style lang="scss" scoped></style>

父组件

import countDownButton from './countDownButton.vue'
const countdownButtonRef = ref<InstanceType<typeof countDownButton> | null>(null)

<countDownButton
ref="countdownButtonRef"
:style="'height: 44px; width: 114px'"
:total-seconds="60"
@on-press="sendSMS"
/>
if (countdownButtonRef.value) {
countdownButtonRef.value.start();
}
作者

陈桥驿站

发布于

2024-10-24

更新于

2024-11-12

许可协议

评论