Attribute Inheritance — Vue

Di Vue, atribut yang diberikan ke komponen tapi tidak dideklarasikan sebagai props akan otomatis diteruskan ke elemen root komponen. Ini disebut fallthrough…

Di Vue, atribut yang diberikan ke komponen tapi tidak dideklarasikan sebagai props akan otomatis diteruskan ke elemen root komponen. Ini disebut fallthrough attributes atau $attrs.

<!-- Parent -->
<MyButton class="primary" id="submit-btn" />

<!-- MyButton.vue — atribut diteruskan ke root -->
<template>
  <button>Klik</button>
  <!-- Hasilnya: <button class="primary" id="submit-btn">Klik</button> -->
</template>

Menonaktifkan inheritance:

<script setup>
defineOptions({ inheritAttrs: false })
</script>

<template>
  <div>
    <button v-bind="$attrs">Klik</button>
    <!-- Atribut diterapkan ke button, bukan div -->
  </div>
</template>

useAttrs():

<script setup>
import { useAttrs } from "vue"
const attrs = useAttrs()
// attrs.class, attrs.id, dll
</script>

Fallthrough attributes berguna untuk komponen wrapper yang meneruskan atribut ke elemen dalam.

Yang akan kamu pelajari