Jørgen S
Jørgen S

Reputation: 71

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

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>

Upvotes: 7

Views: 4144

Answers (2)

Marko Mahnič
Marko Mahnič

Reputation: 735

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").

Upvotes: 2

Mishen Thakshana
Mishen Thakshana

Reputation: 1534

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

Upvotes: 1

Related Questions