vue 单击父按钮单击子组件中的按钮

时间:2021-01-25 19:58:57

标签: vue.js vuejs2 vue-component vuex

我有带按钮的子组件。点击按钮调用方法。

enter image description here

我想在父组件中创建按钮。单击按钮会像单击所有子组件中的第一个按钮一样。在 vue 中怎么做?

enter image description here

沙盒: https://codesandbox.io/s/blazing-dew-zmsky

1 个答案:

答案 0 :(得分:1)

您可以使用 refs 访问所有子组件,以便能够为每个子组件调用一个方法:

<template>
  <div id="app">
    <HelloWorld v-for="i in 4" :key="i" ref="childs"/>

    <button class="allin" @click="click">Click to select 1m in all childs</button>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  methods: {
     click () {
       for (const child of this.$refs.childs) {
         child.changePeriod(0)
       }
     }
  }
};
</script>