Good day!
Let's say I want to use Vue with options api but also do not want to use mixins as they causes a lot of problem. I want to use composables as mixins to give namespacing for mixins/composables.
So, my "solution" was to combine options api and composition api.
Let's say I have a mixin like this:
export default {
data() {
return {
person: {
first_name: 'first name',
last_name: 'last name',
},
gender: 'gender'
}
}
So I decided to convert it into a composable as follows:
export default () => {
const person = reactive({first_name: 'fn', last_name: 'ln'});
const gender = ref('gender');
return {
person,
gender,
}
}
So, in my .vue file I can import the composable:
<script lang="ts">
import useDataComposable from './dataMixin';
...
export default defineComponent({
...
setup() {
const dataComposable = useDataComposable();
dataComposable.gender.value = 'gender2';
dataComposable.person.first_name = 'first name2';
return {dataComposable};
},
created() {
// I want to use data and methods inside the composable as namespace.attribute
// eg:
console.log(this.dataComposable.person.first_name) // => returns 'first name2'
// However,
console.log(this.dataComposable.gender // does not return 'gender2';
// but returns Ref object.
...
I know that I can destructure the composable in the setup function and return it:
<script lang="ts">
import useDataComposable from './dataMixin';
...
export default defineComponent({
...
setup() {
const {person, gender}= useDataComposable();
return {
person, gender,
};
},
created() {
console.log(this.person.first_name) // => returns 'first name2'
// However,
console.log(this.gender // returns 'gender2';
...
However, there is no point to it, as it is anyway it is going to be mixed up with component state.
Also, I could just use mixins with only one object, but I am not sure about it.
export default {
data() {
return {
state: {
person: {
first_name: 'first name',
last_name: 'last name',
},
gender: 'gender',
myMethod: function() {...},
computed: function() {...}
},
created() {...},
onMounted() {...},
watch: {
gender(value) {...}.
},
}
}
I am curious whether it is possible to do what I want.
Is there any way to use object with reactive and ref elements from composable in options api vue code?
Thanks in advance!