【问题标题】:Click event on vue component that was pass down to slot传递给插槽的 vue 组件上的单击事件
【发布时间】:2019-12-21 13:40:14
【问题描述】:

我的自定义滑块插件中有这两个组件,component 1 将是包装器,component 2 将传递给 component 1强>槽:

comp1.vue:

<template>
    <div id="sliderwrapper">
        <slot></slot>
    </div>
</template>

comp2.vue:

<template>
    <div class="slider">
        <slot></slot>
    </div>
</template>

现在,在我的 Vue 应用程序中,我这样做了

<sliderwrapper>
    <sliderbox @click="slideritem(item.title)" v-for="(item,index) in slideritems" :key="index">
        <p>{{ item.title }}</p>
    </sliderbox>
</sliderwrapper>

import sliderwrapper from './comp1.vue';
import sliderbox from './comp2.vue';

export default{
    components : [ sliderwrapper, sliderbox ],
    data() {
        return {
            slideritems : [
                { title : 'title 1' },
                { title : 'title 2' },
                { title : 'title 3' },
            ]
        }
    },
    methods : {
        slideritem(title){
            alert(title);
        }
    }
}

很遗憾,组件 2 &lt;sliderbox&gt; 上的点击事件不起作用也未触发,未附加事件之类的东西。

有什么想法吗?

【问题讨论】:

  • sliderbox 组件是否发出click 事件?如果没有,那么您需要使用 @click.native 来监听原生 DOM 事件。
  • @skirtle 你能发表答案吗?

标签: vue.js vuejs2 vue-component vue-cli


【解决方案1】:
v-on:click.native="slideritem(item.title)"

应该这样做。

【讨论】:

    【解决方案2】:

    在组件上使用@click 只会监听该组件使用$emit 显式发出的click 事件。它不会监听 DOM 事件。

    要侦听本机事件,您需要改用 @click.native

    见:

    https://vuejs.org/v2/guide/components-custom-events.html#Binding-Native-Events-to-Components

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 2019-01-21
      • 2020-04-23
      • 2021-02-05
      • 2017-08-19
      • 2021-07-11
      • 2021-12-29
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多