How to extract common props with vue3 in SFC `<script setup>`
Sometimes we can extract common props using props
in defineComponent
function as below. Both works in vue2/vue3 but not in SFC.
// common-props.js
export default {
commonProps: {
enabled: Boolean,
readonly: Boolean,
}
}
// my-component.vue
import { commonProps } from './common-props';
export default {
props: {
...commonProps,
visible: Boolean,
text: {
type: String,
default: '',
}
}
};
But when I upgrade to <script setup>
. The props
is defined by defineProps
which is a compiler macro. I have to try to use typescript extended the props as follow. But the mixined props is not visible from DevTools.
// common-props.ts
export interface CommonProps{
enabled?: boolean,
readonly?: boolean,
}
// my-component.vue
<script setup lang="ts">
import CommonProps from './common-props';
interface MyComponentProps extends CommonProps {
visible?: boolean,
text?: string,
}
const props = withDefaults(defineProps<ICheckBoxProps>(), {
visible: false,
text: '',
});
</script>
My question is how to extract props from SFC components. And make the Vue Devtools can recognize the extracted props.
Type-only props/emit declarations
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
Currently complex types and type imports from other files are not supported. It is theoretically possible to support type imports in the future
So short answer is no, it is currently not possible to use imported types when using Type-only props declaration
But you can still use non-type (object based) prop declaration inside script setup
// CommonProps.js
export default {
enabled: Boolean,
readonly: Boolean,
}
// Component.vue
<script setup lang="ts">
import {ref} from "vue";
import CommonProps from "./CommonProps.js"
const props = defineProps({
...CommonProps,
items: {
type: Array,
default: () => []
}
})
</script>
<template>
<pre>{{ props }}</pre>
</template>
Demo