我试图在鼠标单击按钮或按下某个键时触发按钮,但我对组件之间的通信感到困惑。我应该如何从其父组件中调用KeyButton组件中的pressDown(),或者是否有更好的方法来实现此功能?
这是我的尝试
按钮的容器
<template>
<key-button :message="'Msg'" :callback="pressKey" ></key-button>
</template>
<script setup>
import KeyButton from "./KeyButton.vue";
import {ref,onMounted} from "vue";
onMounted(()=>{
addEventListener('keypress',(e)=>{
//trigger button
});
})
const pressKey = () => {
//exec when button clicked
}
</script>KeyButton组件
<template>
<button class="button" :class="{'animate': active}" v-on="{mousedown:pressDown,animationend:triggerAnim}">{{props.message}}</button>
</template>
<script setup>
import {ref,defineProps} from 'vue';
const props = defineProps({
message: String,
callback: Function
})
const active = ref(false);
//Function to trigger button
const pressDown = ()=>{
props.callback();
triggerAnim();
}
const triggerAnim = ()=>{
active.value = !active.value;
}
</script>
<style scoped>
button{
display: flex;
height: 5rem;
width: 5rem;
justify-content: center;
align-items: center;
font-size: 2rem;
color: white;
border-color: deepskyblue;
border-width: 0.15rem;
border-radius: 50%;
background-color: lightskyblue;
margin-bottom: 1rem;
margin-left: 2rem;
outline: none !important;
}
.animate{
animation: zoom 0.2s;
}
@keyframes zoom {
0%{
transform: scale(1);
}
10%{
transform: scale(0.9);
}
100%{
transform: scale(1);
}
}
</style>发布于 2021-03-30 03:53:57
您不应该将回调作为道具在组件之间传递。Vue有一个在组件之间共享功能的模式:enter link description here,提供/注入模式。
不过,我建议您遵循前面给出的方法,通过将子组件上的事件发送到父组件来处理vue提供的事件处理。
发布于 2021-03-30 01:30:36
您不应该在vue中将方法作为道具传递,因为这会在组件之间创建相互依赖关系,并降低组件的可重用性。
您应该在按键时从KeyButton组件发出一个事件,并在父组件中侦听它,而不是传递该方法,如下所示:
// KeyButton Component
<button @click="$emit('button-pressed')" />
// Parent
<KeyButton @button-pressed="pressKey" />https://stackoverflow.com/questions/66858644
复制相似问题