[Vuejs]-Combine v-bind=$attrs with custom attributes in Vue3

1👍

As explained in the documentation, the attributes can be used in script block:

If you do not want a component to automatically inherit attributes, you can set inheritAttrs: false in the component’s options.

If needed, you can access a component’s fallthrough attributes in

using the useAttrs() API

If not using , attrs will be exposed as a property of
the setup() context

Note that although the attrs object here always reflects the latest
fallthrough attributes, it isn’t reactive (for performance reasons).
You cannot use watchers to observe its changes. If you need
reactivity, use a prop. Alternatively, you can use onUpdated() to
perform side effects with the latest attrs on each update.

So it’s supposed to be:

  inheritAttrs: false,
  setup(props, ctx) {
    const attrs = ref(ctx.attrs);

    onUpdated(() => {
      attrs.value = ctx.attrs;
    });

    const inputAttributes = computed(() => ({
      ...attrs.value,
      'aria-required': props.required,
      'aria-invalid': !!props.errorMessage,
    }));

    ...

This cannot be achieved with script setup because macros like useAttrs cover only the common cases.

0👍

Following the documentation, you’ll need to add the inheritAttrs to false in your script setup.

Leave a comment