vue 组件之间通信的多种方案(2)
二、嵌套组件通信传值
$attr 与 $listeners 是 v 2.4 版本新增实例property
$attr 作用于上层作用域即父组件,它会将父组件的所有attribute(prop传递的属性、class 与 style)除外
实例:
父组件代码
<div id="app"> <child name="zs" age="18" :gender="'男'" class="child"></child> </div>
子组件代码
<template> <div class="child-deep"> <child-deep v-bind="$attrs"></child-deep> <button type="button" @click="getAttr">button</button> </div> </template> <script> import ChildDeep from '@/components/ChildDeep' export default { name: "Child", // props: ['name', 'age', 'gender'], // 当中间组件通过 props 接收上级组件传递参数是再下级组件获取不到上级组件传递attribute components: { ChildDeep }, data() { return { value: null } }, methods: { getAttr() { const { name, age, gender } = this; console.log(name, age, gender) // zs 18 男 } } } </script>
最下级组件
<template> <div class="child-deep"> <button type="button" @click="getAttr">button1</button> </div> </template> <script> export default { props: ['name', 'age', 'gender'], methods: { getAttr() { const { name, age, gender } = this; console.log(name, age, gender) // zs 18 男 } } }
2、$listeners
$listeners 包含了父作用域中的 (不含 .native
修饰器的) v-on
事件监听器, 即当父组件中触发 $listners 绑定方法后可直接调用该方法
最下级组件示例:
<template> <div class="child-deep"> <button type="button" @click="getAttr">button1</button> </div> </template> <script> import ChildDeepDeep from '@/components/ChildDeepDeep' export default { props: ['name', 'age', 'gender'], components: { ChildDeepDeep }, methods: { getAttr() { $listeners.getListeners({ name: 'ls' }) } } } </script>
子组件代码示例:
<template> <div class="child-deep"> <child-deep v-on="$listeners"></child-deep> </div> </template>
父组件代码示例:
<template> <div id="app"> <child @getListeners="getListeners"></child> </div> </template> <script> import Child from "@/components/Child"; export default { name: "App", components: { Child, }, methods: { getListeners({ name }) { console.log(name) } } }; </script>
PS: $attrs 与 $listeners 更适用于对组件的二次封装