(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="发送" @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>
网友评论