7

I want to access the "name" variable from <script> in my <script setup> block. I cant seem to figure out how to do it. I have tried importing options from '*.vue' but that prompts me to install module '*.vue'.

<script>
export default {
 name: 'some name'
}
</script>
<script setup>
 //use the 'name' variable here
</script>
5
  • 3
    This may be a case of the XY Problem. Why do you want to access the name property? It defines the display name of the component, and otherwise is only used for self-reference in the template. There should be no reason to need it in a component's code. Commented Aug 10, 2022 at 15:40
  • Thanks, I kinda agree. But im refactoring a component, and the store makes use of component names, so I was hoping i did not need to refactor the store as well Commented Aug 10, 2022 at 20:35
  • 1
    You can't do this because name is forced to be filename in script setup. If generated name is acceptable, you can use getCurrentInstance().proxy.$options.name , but it's not reliable Commented Aug 10, 2022 at 21:16
  • The name is not forced, it is inferred. You can still set a custom name if you want. Then you should be able to use getCurrentInstance().proxy.$options.name and get that name. Try it and tell us what happens :) Commented Aug 11, 2022 at 14:26
  • Would this be an okay way to solve it maybe? <script> import NAME_CONSTANT from 'someFile' export default { name: NAME_CONSTANT } </script> <script setup> //use NAME_CONSTANT here </script> Commented Aug 12, 2022 at 7:58

2 Answers 2

2

You can access options exported from <script> by creating a circular dependency to the Vue component:

<script>
  export default { name: "MyComponent" }
</script>

<script setup>
// HACK: Create a circular dependency to this file to get access to options.
import ThisComponent from "./MyComponent.vue"

console.log(`Setting up ${ThisComponent.name}`);

</script>

It also works with TypeScript (lang="ts").

Sign up to request clarification or add additional context in comments.

Comments

1

Unfortunately, this thing can't be done. You could use ref and access its value anywhere in the file.

<template>
 <h1>{{ name }}</h1>
</template>

<script setup>
import {ref} from 'vue';

const name = ref('Jorgen');

</script>

If you want to access it's value inside <script setup> you have to use .value.I have provided the following example in case you want to use it inside a method within <script setup>,

<script setup>
import {ref} from 'vue';

const name = ref('Jorgen');

const showMyName = () => {
   alert(name.value);
}

</script>

In brief, if you want to use name inside the template don't use .value, if you want to use name inside use .value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.