Vue 3: How to get and modify set variables in component functions
P粉463840170
P粉463840170 2023-08-24 19:32:40
0
1
529
<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粉463840170
P粉463840170

reply all(1)
P粉506963842

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!