父组件
<!--父组件 Father.vue-->
<template>
<div>
<!--.sync 子组件可以修改父组件内容 <child :page.sync="page"> </child>
this.$emit("update:page", newVal) -->
<Child :articleList="articleList" @aaa="bbb"></Child>
</div>
</template>
<script>
import Child from './child'
export default {
name: "Father",
components:{
Child,
},
data(){
return {
articleList: ['红楼梦', '西游记', '三国演义'],
}
},
methods:{
bbb(evtValue){//获取子组件传来的数据
console.log('子组件传过来的数据',evtValue);//{age: 20,job: "web",name: "小李
子",sex: "male"}
}
}
}
</script>
子组件
<!--子组件 Child.vue-->
<template>
<div id="ctn-tex">
<ul>
<li v-for="(value,index) in articleList" :key="index">{{value}}</li>
</ul>
<input type="button" @click="emitIndex()" value="向父组件发送数据">
</div>
</template>
<script>
export default {
name: "Child",
props:['articleList'],//接收父组件传来的数据articleList
data(){
return {
info : {
name : "小李子",
age : 20,
sex : "male",
job : "web"
}
}
},
methods:{
emitIndex(){
let obj = this.info;
this.$emit('aaa', obj);//向父组件发射数据obj
}
}
}
</script>
<template>
<div class="outer">
<h3>爷组件</h3>
名字:<input v-model="name">
年龄:<input v-model.number="age" type="number">
电话:<input v-model="phoneNumber">
<child :name="name" :age="age" :phoneNumber="phoneNumber" @fromSun="fromSun"></child>
</div>
</template>
<script>
import Child from "./attrsChild";
export default {
name: 'Parent',
components: {Child},
provide:{
info:"提供数据"
},
data() {
return {
name: 'Tony',
age: 20,
phoneNumber: '1234567890',
fromSunData:''
}
},
methods:{
fromSun(payload) {
console.log("孙传祖", payload);
this.fromSunData = payload;
},
}
}
</script>
<style scoped>
.outer {
margin: 20px;
border: 2px solid red;
padding: 20px;
}
</style>
<template>
<div class="outer">
<h3>父组件</h3>
<div>获得顶层组件的name:{{name}}</div>
<grand-child v-bind="$attrs" v-on="$listeners"></grand-child>
</div>
</template>
<script>
import GrandChild from "./GrandChild";
export default {
components: {GrandChild},
props: ['name'],
created() {
console.log('Child=> $attrs: ' + JSON.stringify(this.$attrs));
}
}
</script>
<style scoped>
.outer {
margin: 20px;
border: 2px solid blue;
padding: 20px;
}
</style>
<template>
<div class="outer">
<h3>孙组件</h3>
<div>顶层组件的name:{{name}}</div>
<div>顶层组件的age:{{age}}</div>
<div>顶层组件的phoneNumber:{{phoneNumber}}</div>
<el-button size="small" type="primary" plain @click="sendToZu">孙传祖</el-button>
</div>
</template>
<script>
export default {
name: "GrandChild",
props: {
name: {
type: String
},
age: {
type: Number
},
phoneNumber: {
type: String
}
},
inject:['info'],
data(){
return{
data:'111'
}},
created() {
// this.parentAge = this.age; //也可以这样取值
console.log('GrandChild=> $attrs: ' + JSON.stringify(this.$attrs));
console.log("接收数据:", this.info) // 接收数据:提供数据
},
methods:{
sendToZu() {
// 孙组件能够触发爷组件的fromSun方法的原因还是因为父组件中有一个$listeners作为中间人,去转发这个事件的触发
this.$emit("fromSun", this.data);
},
}
}
</script>
<style scoped>
.outer {
margin: 20px;
border: 2px solid green;
padding: 20px;
}
</style>