vuejs的动态组件如何添加点击事件。

如图
clipboard.png
其中div的点击事件能够顺利执行,而动态组件中的点击事件则没有反应,即使所渲染的组件本身并没有绑定点击事件也是如此。
给动态组件外层包裹一个div确实能够解决事件捕获的问题,但相应的会带来样式上的问题,望大神指点。

阅读 33k
3 个回答

使用-v-on-绑定自定义事件

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-default/index.css">
</head>
<body>
    <div id="app">
        <component :is="name" @click.native="click"></component>
    </div>
    <!-- 先引入 Vue -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>
        Vue.component('btn', {
            template: '<el-button>按钮</el-button>'
        })

        new Vue({
            el: '#app',
            data: function () {
                return { name: 'btn' }
            },
            methods: {
                click() {
                    console.log('click')
                }
            }
        })
    </script>
</body>
</html>

//parent.vue

<ClassifyItem
        v-for="item in result"
        :industryTitle="item.industryInfo"
        :industryItems="item.industryInfos"
        @tapEvent="linkTap"
/>
        methods: {
            linkTap(data){
                //dosomething
            }
        }

child.vue

<a @click="toggleTap">子组件</a>
clickEvent(item){
    console.log(item);
    this.$emit('tapEvent',item);
}

如果这个事件是多个组件共用的, 并且父组件不是必须的(或者说, 只是为了让一些事件在该作用于下才能被使用), 可以考虑把事件写成js模块, 然后在需要用到的组件中导入.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题