How to access name in <script> from <script setup> in Vue3?
Asked Answered
A

2

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>
Amaral answered 10/8, 2022 at 15:20 Comment(5)
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.Stanchion
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 wellHafiz
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 reliablePilatus
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 :)Stanchion
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>Hafiz
A
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").

Anderlecht answered 22/9, 2022 at 18:3 Comment(0)
N
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

Neuburger answered 10/8, 2022 at 15:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.