I'm in the process of converting a project from Vue 2 options api to Vue 3 composition api.
In a options api component i have a variable called componentData, and from this component i'm calling a mixin. When i call the mixin, i can access all the component's variables from inside of the mixin, here is an example:
//myMixin.js
export default {
methods: {
data_changed() {
//where componentData is declared in the component
console.log(this.componentData)
this.componentData = [1, 2, 3]
},
data() {
return {
someVar: null
}
}
}
I'm having a lot of troubles doing the same with the composition api. Instead of mixins, i have composables, so say i have a component where i'm declaring a variable:
import { ref } from 'vue'
import { testData } from '../mixins/useData.js'
export default {
setup() {
const componentData = ref([])
testData()
}
}
And my composable useData.js:
export function testData() {
console.log(componentData.value) //undefined
componentData.value = [1, 2, 3] //will throw error
}
In this case, the composable will return undefined. How can i access the component's data without passing them as function parameters? Is that because in Vue3 composables are only supposed to return a value and they don't work the same as mixins? Is it possible to change the value of componentData from the composable?
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)
}
}