理论上,父子通讯,小子听老子的就好。但是实际上,有交流才有进步,独裁专政往往没什么有结果。
因此通讯原理是调用了父组件身上的方法。
详情请看代码,其中吧上次代码中的孙子给剔除了。
代码不佳,请多多包涵和指教!!
ps:注意 区域,其为实际作用区域!!!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
table{
font-size: 10px;
width: 500px;
}
th,td{
border: 1px solid lightgrey;
}
.green th{
color: white;
background: #5FB878;
border: 1px solid lightgrey;
}
.gray td{
background: #eeeeee;
border: 1px solid lightgrey;
}
.white td{
background: white;
border: 1px solid lightgrey;
}
button{
background: #5FB878;
border: none;
border-radius: 2px;
}
</style>
</head>
<body>
<div id="app">
<v-parent :pmsg="msg" :paage="age"></v-parent>
</div>
<!--父组件-->
<template id="parent">
<div>
<table cellspacing="0">
<tr class="green">
<th colspan="3">父组件数据</th>
</tr>
<tr class="gray">
<td>name</td>
<td>{{pmsg1}}</td>
<td><input type="text" v-model="pmsg1" ></td>
</tr>
<tr class="white">
<td>age</td>
<td>{{page1}}</td>
<td><input type="text" v-model="page1"></td>
</tr>
</table>
<!--!!!!!!!!!!!!!!-->
<!--父组件向子组件 传递 方法,使用的是 事件绑定机制——“v-on”可以使用“@”代替
当我们自定义了一个事件属性,子组件就能通过某些方式,来调用或传递进 这个方法-->
<v-son :smsg="pmsg1" :sage="page1" @func="tofather"></v-son>
</div>
</template>
<!--子组件-->
<template id="son">
<div>
<table cellspacing="0">
<tr class="green">
<th colspan="3">子组件数据</th>
</tr>
<tr class="gray">
<td>name</td>
<td>{{smsg1}}</td>
<td><input type="text" v-model="smsg1" ></td>
</tr>
<tr class="white">
<td>age</td>
<td>{{sage1}}</td>
<td><input type="text" v-model="sage1"></td>
</tr>
</table>
<!--!!!!!!!!!!!!!!-->
<!--子组件中的按钮,点击触发父组件传递来的“func”法方, 所以自身绑定一个点击方法-->
<button @click="myclick" >儿子传值</button>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el:"#app",
data:{
msg:"baby,let me see your special",
age:"18"
},
components:{
"vParent":{
//注册 注意此处为 paage 不建议page
props:["pmsg","paage"],
template:"#parent",
data:function () {
return{
//使用一个变量接住 msg的值
pmsg1:this.pmsg,
page1:this.paage
}
},
<!--!!!!!!!!!!!!!!-->
//在父组件 methods上写一个供子组件调用的方法:
methods:{
tofather(data){//注释该行,开放下列两行则是多个参数
// tofather(data,data2){
// console.log('如果儿子调用了我,我就出现了'+data+data2);
console.log('如果儿子调用了我,我就出现了'+data);
this.pmsg1=data;//我们可以这样子修改父组件中的值。
}
},
//监听,可以解决 因使用三级同调一个 msg 而报的警告 ,并可以是pmsg1 和 page1 的值不因为上面data导致定死,随着更改而更改
watch:{
pmsg(val){
this.pmsg1=val;
},
paage(val){
this.page1=val;
}
},
//子组件注册
components:{
"vSon":{
props:["smsg","sage"],
template:"#son",
data:function () {
return{
smsg1:this.smsg,
sage1:this.sage
}
},
watch:{
smsg(val){
this.smsg1=val;
},
sage(val){
this.sage1=val;
}
},
methods:{
myclick(){
console.log(1);//检测是否绑定上;
<!--!!!!!!!!!!!!!!-->
//这里有各重要知识点:当点击子组件按钮d的时候,如何拿到父组件传递过来的func方法,并调用这个方法??
//ok,我们当然使用——this!!this所指向的是儿子子组件即我们的vson;
//然后使用$emit————翻译为“触发,调用”, 显然我们要调用的是func
this.$emit('func',123) //传递成功后,$emit()可以传不止一个参。我们在‘func’后面添加一个参数,是我们传的值
//下面注释为传多个参数,相对于父组件接受时要有两个形参接受
//this.$emit('func',123,456)
}
}
}
}
}
}
})
</script>
</body>
</html>
既然有父子,有子父,那么兄弟(同级)呢?