(1)子訪問父組件:props
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="./vue.js"></script>
</head>
<body>
<div id="box">
<aaa></aaa>
</div>
<template id="aaaaa">
<h1>a組件-----{{msg}}</h1>
<bbb :mm="msg"></bbb>
</template>
<script type="text/javascript">
var vm = new Vue({
el:"#box",
components:{
"aaa":{
data(){
return {
msg:'shuju123'
}
},
template:"#aaaaa",
components:{
"bbb":{
props:{
'mm':String
},
template:"<h2>bbbbb----{{mm}}<h2>"
}
}
}
}
})
</script>
</body>
</html>
(2)父訪問子組件:$emit
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="./vue.js"></script>
</head>
<body>
<div id="box">
<aaa></aaa>
</div>
<template id="aaa">
<span>父組件-----{{msg}}</span>
<br>
<input type="button" value="按鈕" name="">
<bbb @sendata="getData"></bbb>
</template>
<template id="bbb">
<h2>子組件----{{msg2}}</h2>
<input type="button" value="發(fā)送" @click="send">
</template>
<script type="text/javascript">
var vm = new Vue({
el:"#box",
components:{
"aaa":{
data(){
return {
msg:"123"
}
},
methods:{
getData(msg){
this.msg = msg
}
},
template:"#aaa",
components:{
"bbb":{
data(){
return {
msg2:"456"
}
},
methods:{
send(){
this.$emit("sendata", this.msg2)
}
},
template:"#bbb"
}
}
}
}
})
</script>
</body>
</html>
(3)兄弟組件通信:子1傳給父組件,父再傳給子2
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="./vue.js"></script>
</head>
<body>
<div id="box">
<aaa></aaa>
</div>
<template id="aaa">
<h1>父組件-----{{msga}}</h1>
<bbb :msgb=msga></bbb>
<ccc @sendata="getdata"></ccc>
</template>
<template id="bbb">
<h2>子組件b-----{{msgb}}</h2>
<br>
<input type="button" value="b" name="">
</template>
<template id="ccc">
<h2>子組件b-----{{msgc}}</h2>
<br>
<input type="button" value="c" @click="send">
</template>
<script type="text/javascript">
var vm = new Vue({
el:"#box",
components:{
"aaa":{
data(){
return {
msga:"aaaaaaaaa"
}
},
methods:{
getdata(msg){
this.msga = msg
}
},
template:"#aaa",
components:{
"bbb":{
props:{
msgb:String
},
template:"#bbb"
},
"ccc":{
data(){
return {
msgc:"cccccccccc"
}
},
methods:{
send(){
this.$emit("sendata", this.msgc)
}
},
template:"#ccc"
}
}
}
}
})
</script>
</body>
</html>