How to define `name` and `inheritAttrs` in `<script setup>`?

13.3k Views Asked by At

Options API:

<script>
  import { defineComponent } from 'vue'

  export default defineComponent({
    name: 'CustomName', // 
    inheritAttrs: false, // 
    setup() {
      return {}
    },
  })
</script>

How to do that in <script setup>, is there an equivalent for name and inheritAttrs like defineProps and defineEmits?

<script setup>
  //  how to define them here?
</script>
4

There are 4 best solutions below

4
On BEST ANSWER

With Vue ^3.3, you can now use defineOptions() directly:

<script setup>
  defineOptions({
    name: 'CustomName',
    inheritAttrs: false,
    customOptions: {},
  })
</script>

The <script setup> syntax provides the ability to express equivalent functionality of most existing Options API options except for a few:

  • name
  • inheritAttrs
  • Custom options needed by plugins or libraries

If you need to declare these options, there're two ways:

  1. If using Vue Macros, you can use defineOptions(), this might be the most succinct approach:
<script setup>
  defineOptions({
    name: 'CustomName',
    inheritAttrs: false,
    customOptions: {},
  })
</script>
  1. If you don't want to rely on external libraries, you can use a separate normal <script> block with export default:
<script>
  export default {
    name: 'CustomName',
    inheritAttrs: false,
    customOptions: {},
  }
</script>

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

Compiled output:

<script>
  export default {
    name: 'CustomName',
    inheritAttrs: false,
    customOptions: {},
    setup() {
      // script setup logic
    },
  }
</script>
0
On

there is a vite plugin vite-plugin-vue-setup-extend can resolve set component name.

config

// vite.config.ts
import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

export default defineConfig({
  plugins: [
    VueSetupExtend()
  ]
})

usage

<script lang="ts" setup name="CompName">
</script>
4
On

You can use defineComponent like this if you want to use setup script and typescript:

<script lang="ts">
export default defineComponent({
  inheritAttrs: false,
});
</script>
<script setup lang="ts">
// Your setup code
</script>

In Vue 3.3 and later, You can define defineOptions inside setup script:

<script setup lang="ts">
defineOptions({
  inheritAttrs: false
})
</script>
0
On

You can use unplugin-vue-define-options to define options API within <script setup>

<script lang="ts" setup>
import { computed } from "vue";
import { useWindowScroll } from "@vueuse/core";

defineOptions({ name: "BackToTop" });

const { y: scrollY } = useWindowScroll();

const show = computed(() => scrollY.value > 180);
</script>