Vue 3: How to get and modify set variables in component functions
P粉463840170
2023-08-24 19:32:40
<p>Consider the following simple example using the composition API in Vue 3. I want to use an instance of <code>test</code> in a component's function. </p>
<pre class="brush:php;toolbar:false;"><script>
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
name: 'Test',
setup(){
let test = ref()
onMounted(() => {
doSomething()
})
return{
test,
doSomething
}
}
})
function doSomething(){
console.log(test) //<-- undefined
console.log(this.test) //<-- undefined
}
</script></pre>
<p>How to access <code>test</code> inside <code>doSomething()</code>? My understanding is that anything returned by <code>setup()</code> should be available throughout the component, just like the <code>data()</code> attribute in the options API. </p>
You must pass
ref
as a parameterAnother method: