.
前言
爷组件
<template>
<div class="page-all">
爷爷组件
<B :msg1="msg1" :msg2="msg2" @method1="handleClick" @method2="handleClick"></B>
</div>
</template>
<script>
import B from "./views/Bpp.vue"
export default {
name: "App",
data() {
return {
msg1: "歌谣爱你呀1",
msg2: "歌谣爱你呀2",
}
},
components: { B },
methods: {
handleClick() {
console.log('爷爷组件')
}
},
mounted() { },
}
</script>
父组件
<template>
<div class="page-all">
父亲组件
<p>$attrs: {{ $attrs }}</p>
<div @click="handleAClick">handleAClick: {{ msg1 }}</div>
<Cpp v-bind="$attrs" v-on="$listeners"></Cpp>
</div>
</template>
<script>
import Cpp from "./Cpp.vue"
export default {
name: "B",
props: ['msg1'],
data() {
return {}
},
components: {Cpp},
methods: {
handleAClick() {
console.log(this.$listeners,"父亲组件")
console.log('父亲组件')
this.$emit('method1')
}
},
mounted() {},
}
</script>
孙组件
<template>
<div class="page-all">
孙子组件
<p>$attrs: {{ $attrs }}</p>
<div @click="handleCClick">handleClick: {{ msg1 }}{{ msg2 }}</div>
</div>
</template>
<script>
export default {
name: "C",
props: ['msg1', 'msg2'],
data() {
return {}
},
components: {},
methods: {
handleCClick() {
console.log(this.$listeners,"孙子组件")
console.log('孙子组件')
this.$emit('method2')
}
},
mounted() {},
}
</script>
定义$attrs
当一个组件没有声明任何 prop 时,$attrs会包含所有父作用域的绑定
(class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部
组件,一般用在子组件的子元素上
运行结果
定义$listeners
包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。
它可以通过 v-on="$listeners" 传入内部组件
运行结果 点击孙子组件
父组件
<template>
<div>
<HelloGeyao></HelloGeyao>
</div>
</template>
<script>
import HelloGeyao from "../src/views/HelloGeyao.vue"
export default {
data(){
return{
msg:"geyao",
}
},
components:{
HelloGeyao
},
provide: function () {
return {
geyao: this.getGeyao // 把当前Vue对象提供给所有子组件可以访问
}
},
methods:{
getGeyao(){
return this.msg
}
}
}
</script>
子组件
<template>
<div class="container">
geyao
</div>
</template>
<script>
export default {
inject:['geyao'],
data() {
return {
}
},
mounted() {
this.createLineChart()
},
methods: {
createLineChart() {
console.log(this.geyao(),"data is")
}
},
components: {
}
}
</script>
<style scoped lang="scss"></style>
运行结果