Vue <script setup>, unable to use defineProps and defineEmits without importing it
Asked Answered
D

2

11

As per the official documentation,

defineProps and defineEmits are compiler macros only usable inside <script setup>. They do not need to be imported and are compiled away when <script setup> is processed.


The problem definition

I'm not able to use defineProps and defineEmits in <script setup> without importing it. Please refer to the error screenshot attached below.

not able to use defineProps without importing it in


The vue code which I'm executing
<!-- HelloWorld.vue -->
<template>
  <h1>{{ props.message }}</h1>
</template>

<script setup>
// import { defineProps } from 'vue';
const props = defineProps({
  message: {
    type: String,
    required: true,
  }
});
</script>

The environment details for reference:
vue ^3.2.6 (3.2.19)
vue-cli @vue/cli 5.0.0-beta.4
node: v14.16.1
npm 6.14.12
Dissert answered 28/9, 2021 at 18:38 Comment(0)
D
6

We can resolve this issue with one of the below solutions.

  1. Create Vue project with Vite. Follow this link for more information.
    yarn create vite <project-name> --template vue
  2. Add below rules in your eslint configuration file. Follow this link for more information.
// .eslintrc.js
module.exports = {
  extends: ['plugin:vue/base'],
  rules: {
    'vue/script-setup-uses-vars': 'error',
  }
}
Dissert answered 12/10, 2021 at 9:2 Comment(2)
In second solution it's wrong link. It should be: link , and code should be: module.exports = { env: { 'vue/setup-compiler-macros': true } }Nightrider
@Lothir: I guess it depends regarding the code. Adding the rules of the answer worked fine for me, while setting the env in your suggestion gave me an error on linting...Bespeak
M
2

use first script:

<script setup>
// import { defineProps } from 'vue';
const props = defineProps({
  message: {
    type: String,
    required: true,
  }
});
</script>

<template>
  <h1>{{ props.message }}</h1>
</template>

and you can use typescript:

<script setup lang="ts">

const props = defineProps<Props>();

interface Props {
  message: string
}

</script>

<template>
  <h1>{{ props.message }}</h1>
</template>
Meseems answered 8/5, 2023 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.