2

If I set a var in setup

 setup(props, context) {
    
        let name = "Tommy";
    }

Is it possible to set this so it can be used in the component?

data() {
    return {
      myName: name
    }
  },

I can access it in the template but not in any of the component methods. Even if I put it in the onMounted hook.

setup(props, context) {
  
    onMounted(() => {
    let name = "Tommy";
    }
}

3 Answers 3

3

The option api behaves differently than composition api, and exchanging properties/methods between the two api is a bad practice, in your case you could define a property in the setup hook and expose it to the template :

import {ref} from 'vue'

 setup(props, context) {
      const name = ref("Tommy");
      
  return{
    myName:name
   }

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

Comments

2

It's possible to use it in the component, and even in the data option:

data() {
    return {
      myname: this.name
    }
}

Though myname won't react to changes in name

Comments

1

Also remember that, if you want to modify the value of your variable within the setup method, if the variable was initialized as a "ref", you have to explicitely access to the .value member

import {ref} from 'vue'

 setup(props, context) {
      const name = ref("Tommy");
      const fullName = name.value + " Hanks"
      
  return{
    myName:name,
    fullName
   }

}

In the template, you don't need to access to the value of the ref returned by the setup method. You just use the ref element, since .value is accessed implicitly in the template.

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.