nat
nat

Reputation: 305

How do you get variables from the setup script in vue3

How would I access variables declared within the setup script within the none setup script? I attempt to update the message in the example below when something happens within the script tags. However, msg just returns undefined, I've looked through the Vue documentation on setup scrips, but there doesn't seem to be any mention of accessing the variable in none setup scripts.

<script setup>

   var msg = 'Hello!';

</script>

<script>

export default {
  data() {
    return {

    };
  },
  mounted(){
   
      // my current attempt to get msg and update it. However, I just get undefined.
      this.msg = 'Something happened inside script tags';
      //or msg = 'Something happened inside script tags';
    
  },

</script>


<template>
  <p>{{ msg }}</p>
</template>

Upvotes: 3

Views: 8641

Answers (1)

Dr4jw3r
Dr4jw3r

Reputation: 181

Seems like you are mixing up two syntaxes here - the newer, Composition API (Vue3, setup script) and Options API (Vue2 style, one with data and mounted functions). While it's still ok to use the Options API syntax, you should only use one of the two. I suggest reading up on the different syntaxes:

Composition API

Options API

The tag is syntactic sugar for THIS type of syntax. Everything returned by the setup() function will be made available to the template. If you're using the tag, by default everything is made available.

For the Options API syntax, everything returned by the data function is made available to the template. Delete the entire first tag and try adding the "msg" property to the object returned by the data function and see if it works.

  data() {
    return {
        msg: ''
    };
  }

Upvotes: 3

Related Questions