一:父子組件通信(對話)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<one></one>
</div>
<script src="vue.js"></script>
<script>
Vue.component('one',{
template:`
<div>
<two @send='news' newName='A'></two>
<two @send='news' newName='B'></two>
<ul>
<li v-for='value in arr'>{{value}}</li>
</ul>
</div>
`,
data:function(){
return{
arr:[]
}
},
methods:{
news:function(txt){
this.arr.push(txt)
}
}
})
Vue.component('two',{
props:['newName'],
template:`
<div>
<label>{{newName}}</label>
<input type='text' v-model='name'>
<button @click='btn'>發(fā)送</button>
</div>
`,
data:function(){
return{
name:''
}
},
methods:{
btn:function(){
this.$emit('send',this.newName+':'+this.name)
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
屏幕展示:對話形式
1.png
2.png
3.png
生命周期
4.png
5.png
代碼展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>{{msg}}</div>
<script src='js/vue.js'></script>
<script>
new Vue({
el:'#app',
data:{
msg:'hello vue'
},
beforeCreate:function(){
alert('beforeCreated');
},
created:function(){
alert('created')
},
beforeMount:function(){
alert('beforMount')
},
mounted:function(){
alert('mounted')
}
})
</script>
</body>
</html>
屏幕展示:彈出多個彈出框beforeCreate;created穗慕;beforeMount妻导;mounted,倔韭,之后出現(xiàn)'hello vue'
6.png
7.png
③非父子傳值:同級之間傳值可以借助第三方(①父傳子:用屬性傳寿酌;②:子傳父:用事件傳)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<one></one>
<two></two>
</div>
<script src="vue.js"></script>
<script>
var q = new Vue();
Vue.component('one',{
template:`
<div>
<h1>這是one組件</h1>
<button @click='bt'>傳送</button>
</div>
`,
data:function(){
return{
msg:'這是一句話'
}
},
methods:{
bt:function(){
q.$emit('send',this.msg)
}
}
})
Vue.component('two',{
template:`
<div>
<h1>這是two組件</h1>
<a href=''>{{msg1}}</a>
</div>
`,
data:function(){
return{
msg1:''
}
},
mounted:function(){
q.$on('send',msg=>{
console.log(this);
this.msg1=msg
})
}
})
new Vue({
el:"#app"
})
</script>
</body>
</html>
屏幕展示:點擊按鈕
8.png
9.png