【问题标题】:How to trigger bootstrap-vue dropdown from outside element?如何从外部元素触发 bootstrap-vue 下拉菜单?
【发布时间】:2022-01-25 09:56:40
【问题描述】:

我正在尝试从外部按钮打开 bootstrap-vue 下拉菜单。例如:

 <b-dropdown>
    <template #button-content>
      Custom <strong>Content</strong> with <em>HTML</em> via Slot
    </template>
    <b-dropdown-item href="#">An item</b-dropdown-item>
    <b-dropdown-item href="#">Another item</b-dropdown-item>
  </b-dropdown>

<b-button @click="openDropdown">Open Dropdown</b-button> 

<script>
methods: {
 openDropdown(){
   // do something
 }
}
</script>

我看到了类似的讨论here。但他们都没有工作。它的任何更新或任何其他方法?

【问题讨论】:

    标签: vue.js bootstrap-vue


    【解决方案1】:

    您链接的 PR 添加了 showhide 方法,可以通过将 ref 添加到 &lt;b-dropdown&gt; 来访问,然后在您的方法中引用此 ref。

    <b-dropdown ref="myDropdown"></b-dropdown>
    
    openDropdown() {
      this.$refs.myDropdown.show();
    }
    

    工作示例

    new Vue({
      el: "#app",
      methods: {
        openDropdown() {
          this.$refs.myDropdown?.show();
        }
      }
    });
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
    <script src="//unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="//unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>
    
    
    <div id="app" class="p-4">
      <b-dropdown ref="myDropdown">
        <template #button-content>
          Custom <strong>Content</strong> with <em>HTML</em> via Slot
        </template>
        <b-dropdown-item href="#">An item</b-dropdown-item>
        <b-dropdown-item href="#">Another item</b-dropdown-item>
      </b-dropdown>
    
      <b-button @click="openDropdown">Open Dropdown</b-button>
    </div>

    【讨论】:

    • 有效! this.$refs.myDropdown?.show();this.$refs.myDropdown.show() 有什么区别?
    • ?.optional chaining,以防引用未定义/为空。
    猜你喜欢
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2020-12-01
    • 2021-07-06
    • 1970-01-01
    • 2012-09-21
    相关资源
    最近更新 更多