Vue關(guān)于子級(jí)組件向父級(jí)組件傳值調(diào)用$emit函數(shù)不生效的問(wèn)題

錯(cuò)誤的示例:

image.png

如果在$emit()中傳入類似chClick這種駝峰命名法的函數(shù)名,函數(shù)將無(wú)法正常啟動(dòng),并且在開(kāi)發(fā)環(huán)境中給予如下提示:


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".

建議
將駝峰命名法更改為以連字符-互相連接的小寫(xiě)字母串或者直接命名為全部小寫(xiě)即可。

<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: ['我和我的祖國(guó)', '建軍大業(yè)', '血戰(zhàn)湘江', '戰(zhàn)狼', '中國(guó)機(jī)長(zhǎng)']
                }
            },
            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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容