这一对方法平时用的不多,最近在复盘基础,发现还是有点生疏。
一,父组件
<!-- Discription: $attrs和$listener, author: ydj, Date: 2021-01-22 15:08:18 -->
<template>
<div>
<childB :name="name" :age="age" @click.native="handleClick" v-on:test1="onTest1" v-on:test2="onTest2"></childB>
</div>
</template>
<script>
import childB from "./chidB";
export default {
components: { childB },
data() {
return {
name: "zhangsan",
age: 20
};
},
computed: {},
methods: {
// 加上.native修饰符之后点击子组件才有效果
handleClick() {
console.log("组件上的点击事件");
},
// 子组件发布触发该方法
onTest1(msg){
console.log('tes1',msg)
this.age = msg
},
// 孙子组件发布触发该方法
onTest2(msg){
console.log('test2',msg)
this.age = msg
}
}
};
</script>
<style lang='scss' scoped>
</style>
二 子组件
<!-- Discription: 儿子组件, author: ydj, Date: 2021-01-22 15:09:10 -->
<template>
<div>
<p>我是子组件</p>
<p>{{$attrs}}</p>
<el-button @click.stop="handleClick">点击</el-button>
<childC v-bind="$attrs" v-on="$listeners"/>
</div>
</template>
<script>
import childC from "./childC";
export default {
// 设置为false后,组件上就不会再显示属性信息
inheritAttrs: false,
// 如果在props中声明了该属性的话,在$attrs中就不存在该传输的值
props: {
name: {
type: String,
default: ""
}
// age: {
// type: Number,
// default: 10
// }
},
components: { childC },
data() {
return {};
},
mounted() {
// 打印的是父组件中不含.native修饰的方法
console.log("子组件", this.$listeners);
},
computed: {},
methods: {
handleClick(){
this.$emit('test1',30)
}
}
};
</script>
<style lang='scss' scoped>
</style>
三 孙子组件
<!-- Discription: 孙子组件, author: ydj, Date: 2021-01-22 15:09:32 -->
<template>
<div>
<p>我是孙子组件</p>
<p>{{$attrs}}</p>
<el-button @click.stop="handleClick">确定</el-button>
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
computed: {},
methods: {
handleClick() {
this.$emit("test2", 40);
}
}
};
</script>
<style lang='scss' scoped>
</style>
四。效果