同级之间的传值1:
body部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<child></child>
<son></son>
</div>
js部分:
<script src="js/vue.js"></script>
<script>
var bus=new Vue()
Vue.component('child',{
template:<h1>这是child</h1> <button @click='sendMsg'>点击按钮传值</button>
,
data:function(){
return{
msg:'这是非父子传值'
}
},
methods:{
sendMsg:function(){
bus.on('send',msg=>{
console.log(this);
this.mess=msg;
})
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
父子组件之间的传值案例:
body部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父子组件传值</title>
</head>
<body>
<div id="app">
<chat-room></chat-room>
</div>
js部分:
<script src="js/vue.js"></script>
<script>
Vue.component('chat-room',{
template:
<div> <ul> <li v-for="(value,index) in chatcont">{{value}}</li> </ul> <user @send='rcvMsg' userName='lhf'></user> <user @send='rcvMsg' userName='lbx'></user> </div>
,data:function(){
return{
chatcont:[]
}
},
methods:{
rcvMsg:function(txt){
this.chatcont.push(txt)
}
}
})
Vue.component('user',{
props:['userName'],
template:`
<div>
<label>{{userName}}</label>
<input type='text' v-model='msg'>
<button @click='sendMsg'>点击发送</button>
</div>
`,
data:function(){
return{
msg:''
}
},
methods:{
sendMsg:function(){
this.$emit('send',this.userName+":"+this.msg)
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
9.png
网友评论