获取 vue 组件的所有实例并在每个实例上运行一个函数 [英] Get all instances of a vue component and run a function on each

查看:52
本文介绍了获取 vue 组件的所有实例并在每个实例上运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Dropdown 的组件.

I have a component called Dropdown.

我使用点击事件触发特定实例:

I trigger specific instances with a click event:

<button @click.stop="$refs.notificationsDropdown.toggleDropdown()"></button>

触发器

toggleDropdown 函数只是改变了 data 中的一个布尔值,如果 true 显示一个 div.

the toggleDropdown function simply changes a boolean value in the data which shows a div if true.

在将此值设置为 true 之前,我想获取 Dropdown 的所有实例并将此值设置为 false,以便所有其他下拉列表在新下拉列表打开之前关闭.

Before this value is set to true, I'd like to get all instances of Dropdown and set this value to false so that all other dropdowns close before the new one opens.

如何获取 Dropdown 的所有实例并在每个实例上运行一个函数来关闭它们的下拉列表?

How can I get all instances of Dropdown and run a function on each of them to close their dropdown?

推荐答案

看起来像 Vuex 状态 可以提供帮助.您可以将 data 中的布尔值更改为 compute 值.
在下拉列表中:

It looks like Vuex state can help. You can change boolean value in data to compute value.
In dropdown:

  computed: {
    isShowed: function() {
      return this.$store.state.activeDropdown === this;
    }
  },
  methods: {
    toggleDropdown: function() {
      if (this.$store.state.activeDropdown === this) {
        this.$store.state.activeDropdown = null;
      } else {
        this.$store.state.activeDropdown = this;
      }
    }
  }

这篇关于获取 vue 组件的所有实例并在每个实例上运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆