美文网首页java学习笔记整理
Vue关于子级组件向父级组件传值调用$emit函数不生效的问题

Vue关于子级组件向父级组件传值调用$emit函数不生效的问题

作者: _借东西的小人 | 来源:发表于2021-07-02 10:44 被阅读0次

    错误的示例:

    image.png

    如果在$emit()中传入类似chClick这种驼峰命名法的函数名,函数将无法正常启动,并且在开发环境中给予如下提示:


    image.png
    vue.js:640 [Vue tip]: Event "chclick" is emitted in component <Cpn> but the handler is registered for
     "chClick". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to 
    camelCase events when using in-DOM templates. You should probably use "ch-click" instead of "chClick".
    

    建议
    将驼峰命名法更改为以连字符-互相连接的小写字母串或者直接命名为全部小写即可。

    <cpn @ch-click="fatClick"></cpn>
    <cpn @chclick="fatClick"></cpn>
    
    this.$emit('ch-click', movies)
    this.$emit('chclick', movies)
    

    完整代码如下:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <!-- 父组件模板 -->
        <div id="app">
            <cpn @ch-click="fatClick"></cpn>
        </div>
        <!-- 子组件模板 -->
        <template id="cpn">
            <div>
                <ul>
                    <li v-for="movies in categories" @Click="liClick(movies)">{{movies}}</li>
                </ul>
            </div>
        </template>
        <script src="../js/vue.js"></script>
        <script>
    
            //子组件
            const cpn = {
                template: '#cpn',
                data() {
                    return {
                        categories: ['我和我的祖国', '建军大业', '血战湘江', '战狼', '中国机长']
                    }
                },
                methods: {
                    liClick(movies) {
                        this.$emit('ch-click', movies)
                    }
                }
            }
            //root 根组件  父组件
            const app = new Vue({
                el: '#app',
                data: {
                },
                methods: {
                    fatClick(movies) {
                        alert(movies)
                    }
                },
                components: {
                    cpn
                }
            })
        </script>
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:Vue关于子级组件向父级组件传值调用$emit函数不生效的问题

        本文链接:https://www.haomeiwen.com/subject/ntyeultx.html