vue实现组件通信的方式有:
<template>
<div>
<p>这是父组件p>
<p>参数: name="fu" age="60" sex="nan-fu" address="shanghai-fu"p>
<hr>
<B name="fu" age="60" sex="nan-fu" address="shanghai-fu" v-bind="$attrs" @setVal="getFuDetail">B>
div>
template>
<script>
import B from './B'
export default {
components: {
B,
},
methods: {
getFuDetail(val) {
console.log('这是父组件的方法', val)
}
}
}
script>
<style>
style>
<template>
<div>
<p>这是子组件p>
<p>参数:name="zi" address="beijing-zi"p>
<p>props: namep>
<p>attrs: {{ $attrs }}p>
<p>因为在B组件中props中包含name, 所以在attrs中,只有age,sex,addressp>
<hr>
<C name="zi" address="beijing-zi" v-on="$listeners">C>
div>
template>
<script>
import C from './C.vue'
export default {
components: {
C,
},
props: {
name: { type: String, default: ''},
},
methods: {
getZiDetail() {
console.log('这是子组件的方法')
}
}
}
script>
<style>
style>
<template>
<div>
<p>这是孙子组件p>
<p>props: agep>
<p>attrs: {{ $attrs }}p>
<p>因为在C组件中props定义了age, 所以attrs中包含:父组件的name, sex, address,子组件的name, address,而子组件的name, address覆盖了父组件的name, addressp>
<hr>
div>
template>
<script>
export default {
props: {
age: { type: String, default: ''},
},
created() {
this.getSunDetail()
},
methods: {
getSunDetail() {
console.log('这是孙组件的方法')
this.$emit('setVal','通过$listeners触发父组件的事件')
}
}
}
script>
<style>
style>

通过$listeners在c组件触发了A组件的方法
