I use Vue 2 with @vue/composition-api plugin.
I made a simple composable:
import { ref } from '@vue/composition-api'
export function useRfp() {
const files = ref([])
return {
files
}
}
And I update the files array in components that use this composable like this: files.value = ...
However, it works only when the composable looks like this:
import { ref } from '@vue/composition-api'
const files = ref([]) // <-- Notice the const is outside the useRfp function
export function useRfp() {
return {
files
}
}
I don't understand why that happens, since in VueJS documentation they have an example with mouse tracker that uses refs inside the function:
// mouse.js
import { ref, onMounted, onUnmounted } from 'vue'
// by convention, composable function names start with "use"
export function useMouse() {
// state encapsulated and managed by the composable
const x = ref(0)
const y = ref(0)
// a composable can update its managed state over time.
function update(event) {
x.value = event.pageX
y.value = event.pageY
}
// a composable can also hook into its owner component's
// lifecycle to setup and teardown side effects.
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
// expose managed state as return value
return { x, y }
}
This makes sense since it's incapsulated inside the function.
By "doesn't work" I mean that when I update the value in one component, it's still empty in another. And it doesn't matter if it's an array or a string.
Why does that happen? I feel like I shouldn't place refs outside the function.