錯誤的示例:
image.png
如果在$emit()中傳入類似chClick這種駝峰命名法的函數(shù)名,函數(shù)將無法正常啟動,并且在開發(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".
建議
將駝峰命名法更改為以連字符-互相連接的小寫字母串或者直接命名為全部小寫即可。
<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: ['我和我的祖國', '建軍大業(yè)', '血戰(zhàn)湘江', '戰(zhàn)狼', '中國機長']
}
},
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>