一:父子组件通信(对话)
<!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'>发送</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,,之后出现'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
网友评论