javascript - vuejs的动态组件如何添加点击事件。
ringa_lee
ringa_lee 2017-04-11 11:38:23
[JavaScript讨论组]

如图

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

ringa_lee
ringa_lee

ringa_lee

全部回复(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>
    <p id="app">
        <component :is="name" @click.native="click"></component>
    </p>
    <!-- 先引入 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模块, 然后在需要用到的组件中导入.

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号