Reputation: 1043
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";
}
}
Upvotes: 2
Views: 3424
Reputation: 63
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.
Upvotes: 1
Reputation: 63059
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
Upvotes: 2
Reputation: 1
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
}
}
Upvotes: 3