vue中组件通信父➡️子通过props
,子➡️父通过$emit
,那么父➡️孙,孙➡️父呢?
通常使用的方法是通过vuex
。如果仅仅是传递数据,而不做其他处理,使用 vuex
处理有点大材小用。
所以就有了 $attrs / $listeners
,通常配合inheritAttrs
一起使用。(注意:是2.4新增的)
例子
<template>
<div>
<child :parent="parentString" :info="info">child>
div>
template>
<script>
import child from "./component_child"
export default {
name: '',
components: { child },
data() {
return {
parentString: "这是父组件",
info: {
name: "张三",
address: "陕西省"
}
}
}
};
</script>
<template>
<div>
<div>{{parent}}div>
<div>子组件:{{$attrs}}div>
<grandson v-bind="$attrs" :message="message">grandson>
div>
template>
<script>
import grandson from './component_grandson.vue'
export default {
name: '',
components: { grandson },
props: [parent],
data() {
return {
message: "这是子组件的传值"
};
},
mounted() {
console.log('child', this.$attrs); //打印出Info的值,(因为parent的值已经被props接收,所以只打印出info)
},
};
</script>
<template>
<div>孙子组件:{{$attrs}}div>
template>
<script>
export default {
name: '',
data() {
return {
};
},
mounted() {
console.log('grandson', this.$attrs);
},
</script>
<template>
<div>
<child :parent="parentString" :info="info" @updateInfo="updateInfo">child>
div>
template>
<script>
import child from "./component_child"
export default {
name: '',
components: { child },
data() {
return {
parentString: "这是父组件",
info: {
name: "张三",
address: "陕西省"
}
}
},
methods: {
updateInfo() {
console.log('更新父组件');
}
},
};
</script>
<template>
<div>
<div>{{parent}}div>
<div>子组件:{{$attrs}}div>
<grandson v-bind="$attrs" :message="message" @childInfo="childInfo">grandson>
div>
template>
<script>
import grandson from './component_grandson.vue'
export default {
name: '',
components: { grandson },
props: [parent],
data() {
return {
message: "这是子组件的传值"
};
},
mounted() {
// console.log('child', this.$attrs); //打印出Info的值,(因为parent的值已经被props接收,所以只打印出info)
console.log('child-listeners', this.$listeners); //updateInfo:f
},
methods: {
childInfo() {
console.log('更新子组件');
}
},
};
</script>
<template>
<div>孙子组件:{{$attrs}}div>
template>
<script>
export default {
name: '',
data() {
return {
};
},
mounted() {
//console.log('grandson', this.$attrs);
console.log('grandson-listeners', this.$listeners); //updateInfo:f childInfo:f
this.$emit('updateInfo') //触发父组件中的updateInfo函数(会打印出父组件打印的值)
},
</script>
以上就是$attrs
和$listeners
的使用,有问题欢迎随时指出!