[Vuejs]-Can i reference global variables in a composable function?

0πŸ‘

You could pass the ref as an argument to testData():

// useData.js
export function testData(componentData) {
  componentData.value = [1, 2, 3] βœ…
}
// MyComponent.vue
import { ref } from 'vue'
import { testData } from '../mixins/useData.js'

export default {
    setup() {
        const componentData = ref([])
                     πŸ‘‡
        testData(componentData)
    }
}

0πŸ‘

As it’s referenced in the documentation you can! You can find the reference under State Management, here I quote:

Although here we are using a single reactive object as a store, you can also share reactive state created using other Reactivity APIs such as ref() or computed(), or even return global state from a Composable:

And they use this code as example:

import { ref } from 'vue'

// global state, created in module scope
const globalCount = ref(1)

export function useCount() {
  // local state, created per-component
  const localCount = ref(1)

  return {
    globalCount,
    localCount
  }
}

Leave a comment