This code was working just fine with vue3 and typescript:
<script lang="ts">
import Vue, { PropType } from 'vue'
enum Position {
TOP = 'top',
RIGHT = 'right',
BOTTOM = 'bottom',
LEFT = 'left',
}
export default {
props: {
position: {
type: String as PropType<Position>,
default: Position.BOTTOM,
},
},
};
</script>
But equivalent code in <script setup>
syntax:
<script setup lang="ts">
enum Activator {
PERSIST = 'persist',
DEMAND = 'demand',
HOVER = 'hover'
}
type Props = {
activator?: Activator
}
const props = withDefaults(defineProps<Props>(), {
activator: Activator.HOVER
});
</script>
The script has less boilerplate but also doesn't work with an error:
Error: [@vue/compiler-sfc] `defineProps()` in cannot reference locally declared variables because it will be hoisted outside of the setup() function. If your component options require initialization in the module scope, use a separate normal to export the options instead. ``` App.vue 13 | 14 | const props = withDefaults(defineProps(), { 15 | activator: Activator.HOVER | ^^^^^^^^^ 16 | }); 17 | at Se (https://sfc.vuejs.org/assets/index.8aa136ef.js:137:75) at https://sfc.vuejs.org/assets/index.8aa136ef.js:141:1419 at Object.enter (https://sfc.vuejs.org/assets/index.8aa136ef.js:76:6842) ```
Isn't it possible to use enums for default value with script setup? Playground
EDIT: It seems that after I export the type from other files it doesn't crash. I'll investigate a little further.
CodePudding user response:
Define the enum
in an other (non-setup) script.
<script setup lang="ts">
type Props = {
activator?: Activator
}
const props = withDefaults(defineProps<Props>(), {
activator: Activator.HOVER·
});
</script>
<script lang="ts"> // here
enum Activator {
PERSIST = 'persist',
DEMAND = 'demand',
HOVER = 'hover'
}
</script>
<template>
<h1>hello world</h1>
</template>
CodePudding user response:
It seems that this synax doesn't support the enum
s according to this
As of now, the type declaration argument must be one of the following to ensure correct static analysis:
- A type literal
- A reference to an interface or a type literal in the same file
You could use a basic type :
<script setup lang="ts">
type Activator = "persist" | "demand" | "hover";
type Props = {
activator?: Activator;
};
withDefaults(defineProps<Props>(), {
activator: "demand",
});
</script>
<template>
<div>{{ activator }}</div>
</template>