$attrs + $listeners 实现跨组件传值

290 阅读1分钟

Vue 父子组件、跨组件数据传递( inheritAttrs + $attrs + $listeners)

v-bind='$sttrs' 实现跨组件传值 / v-on='$listeners' 跨组传递件自定义方法

  • top 组件 内容
// 传递值和自定义事件
<template>
	<div>
		<MyCenter
			name="jp"  
			age="19"
			city="xi,an"
			money="infinity"
			@fun="fun"
			@test="test"
		/>
	</div>
</template>

<script>
import MyCenter from '@/components/center.vue'
export default {
	components: { MyCenter },
	methods: {
		fun() {
			console.log('success')
		},
		test() {
			console.log('test')
		},
	},
}
</script>
  • center 中转组件
<template>
	<div>
        <!-- 通过v-bind='@attrs' 将当前组件props未接收的值绑定到希望得到值的组件上 -->
        <!-- 通过v-on="$listeners" 将所有自定义事件绑定到希望得到自定义方法的组件上 -->
		<MyBottom v-bind="$attrs" v-on="$listeners" />
	</div>
</template>

<script>
import MyBottom from './bottom.vue'
export default {
	components: {
		MyBottom,
	},
	// 中间组件接受了 name 和 age 属性数据,没有接收的值在this.$attrs 对象中
	// city 、money 属性没有接收就在this.$attrs 属性中,通过v-bind='$attrs'绑定给中间组件的子组件就会把属性传递下去
	// 自定义事件存储在this.$listeners 对象中,可以通过 v-on='$listeners'  将自定义事件往下传递
	props: {
		name: String,
		age: String,
	},
}
</script>


  • button 接受数据组件
<template>
  <section>
    <div @click="$listeners.fun">
      {{ $attrs['city'] }}  在$attrs里面只会有props没有注册的属性
      <br>
      {{ money }}
      <el-button @click.stop="$emit('fun')"> test</el-button>
    </div>
  </section>
</template>

<script>
  export default {
    props: {
      money: {
        type: String,
        default: ''
      }
    },
    mounted() {
      console.log(this.$attrs);
      console.log(this.$listeners);
      this.$listeners.test();
      this.$listeners.fun();
    }
  };
</script>