子父通信
子組件跟父級組件通信是通過事件的方式來通信。
使用this.$emit('show',{})不僅觸發(fā)了事件還傳遞了數(shù)據(jù)挖息。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="app">
<father></father>
</div>
<script src="vue.js"></script>
<script type="text/javascript">
Vue.component('father',{
template:`
<div>
<child @show="showfn"></child>
<div v-if="show">成績:88</div>
</div>`,
data:function(){
return {
show:false
}
},
methods:{
showfn:function(data){
this.show = true;
console.log(data);//data是在用$emit觸發(fā)事件時傳遞的數(shù)據(jù)金拒。
}
}
});
Vue.component('child',{
template:'<button @click="onClick">這里是子組件</button>',
methods:{
onClick:function(){
this.$emit('show',{a:1,b:2,c:3});//觸發(fā)事件
}
}
});
new Vue({
el:'#app'
});
</script>
</body>
</html>
- 首先定義兩個組件,父組件father和子組件child;
- 父組件包含子組件套腹;
- 在子組件觸發(fā)相關(guān)事件绪抛,在事件方法里使用$emit('事件名',{要傳遞的數(shù)據(jù)})來觸發(fā)其他事件,這個使事件是在父組件中的子組件內(nèi)監(jiān)聽电禀,然后在父級組件調(diào)用觸發(fā)該事件的對應(yīng)的方法幢码。
簡單的說就是,子組件觸發(fā)相關(guān)事件傳遞給父級組件鞭呕,父級組件進行相關(guān)操作蛤育。