1、什么是同级传值?
同级传值又叫非父子传值,第三方量:var = new Vue();使用$on()事件监听。
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div class="app">
<child></child>
<son></son>
</div>
<script src="js/vue.js"></script>
<script>
var bus = new Vue();
Vue.component("child",{
template:`
<div>
<h1>我是child组件</h1>
<button @click="sendMsg">传递数据给son</button>
</div>
`,
data:function(){
return{
msg:"hello vue!"
}
},
methods:{
sendMsg:function(){
bus.$emit("send",this.msg)
}
}
})
Vue.component("son",{
template:`
<div>
<h1>我是son组件</h1>
<a href="">{{mess}}</a>
</div>
`,
data:function(){
return{
mess:""
}
},
mounted:function(){
bus.$on("send",msg=>{
this.mess=msg
})
}
})
new Vue({
el:".app"
})
</script>
</body>
</html>
运行结果:
image.png2、子级传父级练习:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
ul{
list-style: none;
}
</style>
</head>
<body>
<div class="app">
<my-father></my-father>
</div>
<script src="js/vue.js"></script>
<script>
Vue.component("my-father",{
template:`
<div>
<ul>
<li v-for="value in arr">{{value}}</li>
</ul>
<user @send="rcvMsg" userName="Jack"></user>
<user @send="rcvMsg" userName="Lucy"></user>
</div>
`,
data:function(){
return{
arr:[]
}
},
methods:{
rcvMsg:function(txt){
this.arr.push(txt)
}
}
})
Vue.component("user",{
props:["userName"],
template:`
<div>
<label>{{userName}}</label>
<input type="text" v-model="inputVal">
<button @click="sendMsg">发送</button>
</div>
`,
data:function(){
return{
inputVal:""
}
},
methods:{
sendMsg:function(){
this.$emit("send",this.userName+":"+this.inputVal)
}
}
})
new Vue({
el:".app"
})
</script>
</body>
</html>
网友评论