vue.js - Vue2.0父子组件之间通信
本文介绍了vue.js - Vue2.0父子组件之间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我在子组件中出发父组件的事件,为什么监听不到?
代码如下:
<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
:
<tool-bar :msg="msg" @from-child-msg="listenChildMsg"></tool-bar>
this.$emit('from-child-msg', '这是子组件传递的消息');
補充說明:下面指的字符串模板是指:
{
template: '這裡定義的就叫做符串模板'
}
因為字符串模板是直接可以由 javascript 解析,不用透過瀏覽器方法取得 Dom,所以不受此限制。
这篇关于vue.js - Vue2.0父子组件之间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文