vue中attrs的使用

发布时间 2023-10-30 16:06:57作者: 天官赐福·

vue中attrs的使用

1.attrs的作用

  • 用来进行子孙组件之间的数据传递
  • 接收父组件传过来,但是又没有在props中定义的数据。(class及style除外)

2.父子组件之间数据传递的用法

爷爷组件-grandpa:

<template>
  <div>
    <span>爷爷</span>
    <Son
      :phone="phone"
      sex="男"
      name="张三"
      :age="age"
      style="color: red;"
      class="son"
    />
  </div>
</template>

<script>
import Son from "./son.vue";
export default {
  components: { Son },
  data() {
    return {
      phone: 13212345678,
      age: 34
    };
  }
};
</script>

<style>
.son {
  font-size: 24px;
}
</style>

儿子组件-son:

<template>
  <div>
    <span>儿子-{{ name }} -{{ $attrs.phone }}</span>
  </div>
</template>

<script>
export default {
  // props中定义的数据
  props: {
    name: {
      type: String,
      required: true, //必传
      default: "张三丰" //如果没有父组件传值时默认显示这个
    },
    age: {
      type: Number,
      default() {
        return 36;
      }
    }
  },
  mounted() {
    console.log("son", this.name, this.age, this.$attrs);
  }
};
</script>

<style></style>

son组件中打印的内容:

image

页面显示效果:

image

总结:

  • grandpa组件传过来的数据,如果没有在props中定义,那么数据可以通过this.$attrs获取。
  • attrs中的数据会显示到组件的dom根节点上。
  • 爷爷组件传过来的class及style,不会出现在attrs中,但是会显示到dom根节点上。

3.inheritAttrs-控制组件的根元素是否继承特性

// 不想继承所有父组件的内容,同时也不在组件根元素dom上显示属性
inheritAttrs: false,

在son组件中加入上面代码,则attrs中继承到的grandpa组件传过来的数据就不会在根节点上显示,但是this.$attrs获取到的里面的内容并不会变。

组件打印内容:

image

页面展示效果:

image

4.爷孙组件之间数据传递的用法

儿子组件-son:

给GrandSon使用v-bind="$attrs"绑定一下attrs中的数据,这样GrandSon组件中就能获取到

<template>
  <div>
    <span>儿子-{{ name }} -{{ $attrs.phone }}</span>
    <GrandSon v-bind="$attrs" />
  </div>
</template>

<script>
import GrandSon from "./grandSon.vue";
export default {
  // 不想继承所有父组件的内容,同时也不在组件根元素dom上显示属性
  inheritAttrs: false,
  components: { GrandSon },
  props: {
    name: {
      type: String,
      required: true, //必传
      default: "张三丰" //如果没有父组件传值时默认显示这个
    },
    age: {
      type: Number,
      default() {
        return 36;
      }
    }
  },
  mounted() {
    console.log("son", this.name, this.age, this.$attrs);
  }
};
</script>

<style></style>

4.1通过this.attrs获取数据

孙子组件-grandSon:

<template>
  <div>孙子</div>
</template>

<script>
export default {
  mounted() {
    console.log("grandSon", this.$attrs);
  }
};
</script>

<style></style>

页面展示效果:

grandpa组件传过来的数据会显示到grandSon组件的根节点上

image

组件打印内容:

在grandSon组件中通过this.$attrs可以获取到grandpa组件传过来的数据

image

4.2通过props获取数据

孙子组件中同样可以通过props的形式获取到传过来的数据

孙子组件-grandSon:

<template>
  <div>孙子</div>
</template>

<script>
export default {
  props: {
    phone: {
      type: Number
    },
    sex: {
      type: String
    }
  },
  mounted() {
    console.log("grandSon", this.$attrs, this.phone,this.sex);
  }
};
</script>

<style></style>

页面展示效果:

image

组件打印内容:

image