繁体   English   中英

如何将方法从一个组件传递到另一个组件并在 Vue.js 中使用它?

[英]How to pass a method from one component to another and use it onclick in Vue.js?

所以在我的 App.vue 组件中,我还有另外两个组件正在渲染,我想要实现的是,当用户点击播放按钮时,应该使用组件 ProgressRing 中的 animateRing() 方法,我的代码看起来是下列的:

应用程序

<template>
  <div id="app">
    <ProgressRing>
        <PlayButton
          @click="animateRing(), active = !active"
          :class="{active: active}"
        />
    </ProgressRing>
  </div>
</template>

播放按钮.vue

<template>
  <button class="play-button" @click="$emit('click')">
    ...
    some irrelevant code here
    ...
  </button>
</template>

进度环.vue

<template> 
...some code...
</template>

<script>
export default {
  methods: {
    animateRing(){
      console.log('I'm animated');
    }
  }
};
</script>

我似乎无法找出正确的方法来做到这一点。 使该方法在 App 组件中工作的最佳方法是什么? 我对 Vue 比较陌生,还没有真正弄明白。

这是您可以实现此目的的一种方法:

应用程序

<template>
  <div id="app">
    <ProgressRing ref="progressRing">
        <PlayButton
          @click="animateRing(), active = !active"
          :class="{active: active}"
        />
    </ProgressRing>
  </div>
</template>

<script>
export default {
  methods: {
    animateRing(){
      this.$refs.progressRing.animateRing()
    }
  }
};
</script>

我很好奇PlayButtonProgressRing的孩子,但没有在 ProgressRing.vue 中定义的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM