【问题标题】:Binding button with keypress in Vue3.0Vue3.0中按键绑定按钮
【发布时间】:2021-06-25 17:51:32
【问题描述】:

我试图在鼠标单击或按下某个键时触发该按钮,但我对组件之间的通信感到困惑。我应该如何从父组件调用 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>

按键组件

<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>

【问题讨论】:

    标签: javascript html css vue.js vue-component


    【解决方案1】:

    您不应该在 vue 中将方法作为 props 传递,因为这会在组件之间创建相互依赖关系并降低它们的可重用性。

    您应该在按键时从 KeyButton 组件发出一个事件,而不是传递该方法,并在父组件中监听它,如下所示:

    // KeyButton Component
    <button @click="$emit('button-pressed')" />
    
    // Parent
    <KeyButton @button-pressed="pressKey" />
    

    【讨论】:

      【解决方案2】:

      你不应该在组件之间传递回调作为道具。 Vue 有一个在组件之间共享功能的模式:enter link description here,提供/注入模式。

      尽管如此,我建议你遵循 Aside 给你的方法,并通过向父组件发出子组件上的事件来使用 vue 提供的事件处理。

      【讨论】:

        猜你喜欢
        • 2014-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 1970-01-01
        相关资源
        最近更新 更多