Vue2-$attrs传值操作

86 阅读1分钟

在 Vue 中,使用 $attrs 实现爷爷组件向孙子组件传递数据的流程如下:

  1. 在爷爷组件中,将需要传递给孙子组件的数据绑定到父组件的 $attrs 属性上。
  2. 在父组件中,接收 $attrs 作为爷爷组件传递的属性,并将其传递给孙子组件。
  3. 在孙子组件中, 使用 prop 接收父组件传递的属性,其中包含父组件传递过来的数据,也包含爷爷组件传递给父组件的数据。

示例一:全量传值

在这个示例中,首先爷爷组件 GrandParent.vue 将属性通过 $attrs 传递给父组件 Parent.vue,然后父组件再将这些属性通过 $attrs 传递给子组件 Child.vue。最终,在 Child.vue 中通过 $attrs 属性获取到数据,实现了数据从爷爷组件传递到孙子组件的功能。

  1. 爷爷组件:GrandParent.vue
<template>
 <Parent v-bind="$attrs"></Parent>
</template>

<script>
import Parent from './Parent.vue';
export default {
  components: { Parent }
}
</script>
  1. 父组件:Parent.vue
<template>
  <Child v-bind="$attrs"></Child>
</template>

<script>
import Child from './Child.vue';
export default {
  components: { Child }
}
</script>
  1. 子组件:Child.vue
<template>
  <p>{{ $attrs }}</p>
</template>

示例二:部分传值

在这个示例中,爷爷组件 GrandParent.vue 传递 title 属性给父组件 Parent.vue,父组件再传递 message 属性给子组件 Child.vue。最终在 Child.vue 中分别输出了 titlemessage 的值,实现了部分属性的传递。

  1. 爷爷组件:GrandParent.vue
<template>
  <Parent title="Hello" v-bind="$attrs"></Parent>
</template>

<script>
import Parent from './Parent.vue';
export default {
  components: { Parent }
}
</script>

  1. 父组件:Parent.vue
<template>
  <Child message="Vue" v-bind="$attrs"></Child>
</template>

<script>
import Child from './Child.vue';
export default {
  components: { Child }
}
</script>
  1. 子组件:Child.vue
<template>
  <p>{{ title }}</p>
  <p>{{ message }}</p>
</template>
<script>
export default {
  props: ['title', 'message']
}
</script>