我在子组件中出发父组件的事件,为什么监听不到?
代码如下:
<div id="app">
<list></list>
</div>
<template id="tep">
<div>
<p>hello,这是父组件</p>
<hr/>
<tool-bar :msg="msg" @fromChildMsg="listenChildMsg"></tool-bar>
</div>
</template>
<template id="tep1">
<div>
<p>子组件</p>
<p>{{msg}}</p>
<button @click="subClick">触发父组件事件</button>
</div>
</template>
<script>
var toolBar = Vue.extend({
props:['msg'],
template:"#tep1",
data:function(){
return {
}
},
methods:{
subClick:function(){
console.log(1);
this.$emit('fromChildMsg', '这是子组件传递的消息');
}
}
});
var list = Vue.extend({
template:'#tep',
data: function(){
return {
msg:"父组件传递子组件的数据"
}
},
methods:{
listenChildMsg:function(msg){
console.log(2);
console.log(msg);
},
},
components:{
'tool-bar':toolBar,
},
});
new Vue({
el:"#app",
components:{
list:list
}
});
</script>
点击按钮触发父组件事件,没有console语句输出,这是为什么?
props
會自動轉換,但是自定義事件
似乎不會,所以你得把事件名稱改成kebab-case
:補充說明:下面指的字符串模板是指:
因為字符串模板是直接可以由 javascript 解析,不用透過瀏覽器方法取得 Dom,所以不受此限制。