Home  >  Q&A  >  body text

Vue 3: How to get and modify set variables in component functions

<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>
P粉463840170P粉463840170446 days ago535

reply all(1)I'll reply

  • P粉506963842

    P粉5069638422023-08-25 13:05:01

    You must pass ref as a parameter

    <script>
    import { defineComponent, ref, onMounted } from 'vue'
    
    export default defineComponent({
      name: 'Test',
      setup () {
        let test = ref(null)
    
        onMounted(() => {
          doSomething(test.value)
        })
    
        return {
          test,
          doSomething
        }
      }
    })
    
    function doSomething (param) {
      console.log(param); // null
    }
    </script>
    

    Another method:

    // functions.js
    import { ref } from 'vue'
    export let test = ref(null)
    // vue-file
    <script>
    import { defineComponent, ref, onMounted } from 'vue'
    import { test } from '../utils/functions.js'
    
    export default defineComponent({
      name: 'Test',
      setup () {
    
        onMounted(() => {
          doSomething(test)
        })
    
        return {
          test,
          doSomething
        }
      }
    })
    
    function doSomething (param) {
      console.log(test.value); // <-- instant access
      console.log(param.value); // <-- import via parameter
    }
    </script>

    reply
    0
  • Cancelreply