Vue composition api - pass a variable to my component data() option?

Viewed 1972

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

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

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
   }

}

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.

Related