首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vue3.0中的按键绑定按钮

Vue3.0中的按键绑定按钮
EN

Stack Overflow用户
提问于 2021-03-30 01:14:09
回答 2查看 160关注 0票数 1

我试图在鼠标单击按钮或按下某个键时触发按钮,但我对组件之间的通信感到困惑。我应该如何从其父组件中调用KeyButton组件中的pressDown(),或者是否有更好的方法来实现此功能?

这是我的尝试

按钮的容器

代码语言:javascript
复制
<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组件

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-30 03:53:57

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

不过,我建议您遵循前面给出的方法,通过将子组件上的事件发送到父组件来处理vue提供的事件处理。

票数 0
EN

Stack Overflow用户

发布于 2021-03-30 01:30:36

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

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

代码语言:javascript
复制
// KeyButton Component
<button @click="$emit('button-pressed')" />

// Parent
<KeyButton @button-pressed="pressKey" />
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66858644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档