Adding inheritAttr in vue3 using setup with vite

kalimahapps

Kalimah Apps

Posted on June 11, 2022

Adding inheritAttr in vue3 using setup with vite

When using vue3 composition API you can utilize setup in script tag to write less boilerplate code which makes it easy to maintain in future.

All top-level bindings can be used directly used in the template tag. See this example:



<script setup>
// variable
const msg = 'Hello!'

// functions
function log() {
  console.log(msg)
}
</script>

<template>
  <div @click="log">{{ msg }}</div>
</template>


Enter fullscreen mode Exit fullscreen mode

While this is great in making code more readable it comes with downfalls. Most notable inability to disable attribute inheritance inside script tag with setup attribute.

So in order to disable attribute inheritance using setup you need to add two script tags.



<script>
// use normal <script> to declare options
export default {
  inheritAttrs: false
}
</script>

<script setup>
// ...setup logic
</script>


Enter fullscreen mode Exit fullscreen mode

This works fine but it defies the purpose of writing less boilerplate code.

Using vite, the amazing build tool, I developed a plugin that will enable you to omit the extra <script> declaration.

The new syntax will be like



<script setup inherit-attrs="false">
// ...setup logic
</script>


Enter fullscreen mode Exit fullscreen mode

And that's it. The plugin will add the second <script> tag automatically with inheritAttrs: false.

You can find the plugin, installation and configuration steps here:

GitHub logo kalimahapps / vite-plugin-vue-setup-inherit-attrs

Add inherit-attrs support for vue3 using vite

vite-plugin-vue-setup-inherit-attrs

Add support for inheritAttrs in vue-setup using vite

[!WARNING] You don't need this plugin if you are using Vue 3.3+

Use defineOptions instead.

Install

npm install vite-plugin-vue-setup-inherit-attrs -D


Usage

In vite.config.ts import the plugin and add plugins array:

import { defineConfig, Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import inheritAttrs from 'vite-plugin-vue-setup-inherit-attrs';

export default defineConfig({
  plugins: [vue(), inheritAttrs()],
})
Enter fullscreen mode Exit fullscreen mode

In vue template add inherit-attrs="false":

<template>
  <div class="root-element">
      <div class="nested-element" v-bind="$attrs">
          $attrs will be added to this element instead of the root element
      </div>
  </div>
</template>

<script lang="ts" setup inherit-attrs="false">
  // code here
</script>
Enter fullscreen mode Exit fullscreen mode


Config

No config needed :)

Change Log

1.0.4

  • Moved…




💖 💪 🙅 🚩
kalimahapps
Kalimah Apps

Posted on June 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related