非Prop的Attribute传递

2022/7/21 vue2vue3js

vue中非Prop的Attribute传递 &attrs

# vue中非Prop的Attribute传递

  1. 简单来说就是你在子组件上写个class style 子组件的根组件会继承

示例 示例 示例

  1. 如果不想继承可以在子组件 export default 对象里写 inheritAttrs: false,

# 什么情况下禁用

  1. 一般想把 Attribute 应用在根元素之外的其他元素

# 用法

  1. 第一种用法单个手动
父组件
<template>
  <div id="app">
    <one class="www cc" id="uid cid"></one>
  </div>
</template>

<script>
import one from "./components/one.vue";
export default {
  components: {
    one,
  },
};
</script>


子组件
<template>
  <div>
    <div :class="$attrs.class" :id="$attrs.id">1</div>
  </div>
</template>

<script>
export default {
  inheritAttrs: false,
};
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  1. 第二种直接加载全部的class和id
父组件
<template>
  <div id="app">
    <one class="www cc" id="uid cid"></one>
  </div>
</template>

<script>
import one from "./components/one.vue";
export default {
  components: {
    one,
  },
};
</script>


子组件
<template>
  <div>
    <div v-bind="$attrs">1</div>   这里这里
  </div>
</template>

<script>
export default {
  inheritAttrs: false,
};
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30