javascript - 如何从插槽中调用组件方法 - Vue

标签 javascript vue.js vuejs2

我是 Vue 新手,对 Vue slots 有疑问。我有这样的组件

<template>
<div class="dropDown__container">
  <div
    v-show="isOpened"
    class="dropDown__content"
    style="display:none;"
  >
    <slot />
    <div class="dropDown__container-flex">
      <span
        class="dropDown__button"
        @click="hideDropDown()"
      >
        Clear
      </span>
      <span
        class="dropDown__button"
        @click="hideDropDown(true)"
      >
        Submit
      </span>
    </div>
  </div>
</div>

如您所见,有一个方法 hideDropdown,我想将其传递到我的 slot。为了您的信息,我正在使用这个 slot 像这样

<drop-down>
<div class="d-flex flex-row justify-content-between">
    <ul id="priceFromList" class="hintList hintList--left">
        <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="">
            {{ price }}
        </li>
    </ul>
</div>
</drop-down>

我想要实现的是将 hideDropdown 方法从组件传递到 slot 并在每个 li 的 @click 上使用它。这可能吗 ?我会感谢任何帮助。提前致谢。

最佳答案

The below code syntax is only useable from vue 2.6

好吧,您实际上可以实现它。我不确定这是否是最佳做法。这是实现它的方法。

在你的父组件中将函数绑定(bind)到插槽 <slot :callableFunc="hideDropDown"/>

  <template>
    <div class="dropDown__container">
      <div
        v-show="isOpened"
        class="dropDown__content"
        style="display:none;"
      >
        <slot :callableFunc="hideDropDown"/>
        <div class="dropDown__container-flex">
          <span
            class="dropDown__button"
            @click="hideDropDown()"
          >
            Clear
          </span>
          <span
            class="dropDown__button"
            @click="hideDropDown(true)"
          >
            Submit
          </span>
        </div>
      </div>
    </div>
  </template

在您的子组件中,您将使用作用域插槽来访问绑定(bind)函数。

<drop-down>
<template v-slot:default="{ callableFunc}">
<div class="d-flex flex-row justify-content-between">
    <ul id="priceFromList" class="hintList hintList--left">
        <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="callableFunc()">
            {{ price }}
        </li>
    </ul>
</div>
</template>
</drop-down>

请查看文档https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots

关于javascript - 如何从插槽中调用组件方法 - Vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55412062/

相关文章:

javascript - Vue.Js,如何在 v-for 中使用动态颜色和类

javascript - 是否可以使用 ng 风格的动画? ( Angular )

javascript - 通过jquery中的数组进行多文件上传验证

javascript - 链式 promise - 正确的方法

javascript - 在 Vue.js 应用程序中初始化 firebase 3.4.0

javascript - Vue.js 绑定(bind)对象属性

javascript - 如何通过 Ajax 请求从服务器重定向网站

javascript - axios 获取参数数组

html - VueJS单文件组件如何正确使用 "scoped"样式?

javascript - nextTick : "TypeError: Cannot read property ' key' of undefined"in vue 错误