1.生命周期
image2.父子通讯练习:
Vue.component('chat',{
template:`
<div>
<ul>
<li v-for="value in arr">{{value}}</li>
</ul>
<user @send='rcvMsg' userName='jack'></user>
<user @send='rcvMsg' userName='rose'></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'
})
3.同级传值:
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"
})
网友评论