Reputation: 831
It's said that composition api solves naming conflicts which were brought by mixins.
This is what I found on the internet about composition API.
export default {
setup () {
const { someVar1, someMethod1 } = useCompFunction1();
const { someVar2, someMethod2 } = useCompFunction2();
return {
someVar1,
someMethod1,
someVar2,
someMethod2
}
}
}
I guess, useCompFunction1()
and useCompFunction2
are like mixins. In the example, all is good. but if useCompFunction1()
and useCompFunction2()
use the variable with the same name, we would still have a problem in the above code since we wouldn't be able to use both of the variables. So, naming conflicts are of course still there. Then why does it say that naming collisions are solved with Composition API?
UPDATE:
The example I provided, with it, This is the code I found how reusable code should be written.
import { ref, computed } from "vue";
export default {
setup() {
const count = ref(0);
const double = computed(() => count.value * 2)
function increment() {
count.value++;
}
return {
count,
double,
increment
}
}
}
As you can see, it returns variables with count
, double
, increment
. The way it does is the caller should know the names of it to use it. So, it's still composition which decides what to name the variables. Any idea ?
Upvotes: 3
Views: 1866
Reputation: 37753
The main difference between mixin
and composition function is that mixin
decides about variable names it provides but with composition function, YOU decide about the names of the variables YOU assign from the result the composition function provides...
Example:
const { someVar1, someMethod1 } = useCompFunction1();
const { someVar1, someMethod1 } = useCompFunction2();
....most of the IDE's tells you this is not correct as you are declaring variables which already exist...
The point is, it doesn't matter what are the variable names inside useCompFunction1
or useCompFunction2
as those are local variables. But to use them You need to declare your own variables and assign it from the composition function result...so you decide about the variable name, not the 'mixin' you are using...
So, it's still composition which decides what to name the variables
No, its You!
If you use result as-is:
const comp1 = useCompFunction1();
...you use the result with the name you choose:
console.log(comp1.count)
However if you choose to use destructuring, you can still rename the variables you get:
const { count: count1, double: double1, increment: increment1 } = useCompFunction1();
...now you can use variables count1
, double1
and increment1
as you see fit...
Upvotes: 7
Reputation: 9108
You can rename the variables, e.g. lets assume both useCompFunction1()
and useCompFunction2()
returns testVar
variable:
const { testVar: testVar1, someMethod1 } = useCompFunction1();
const { testVar: testVar2 } = useCompFunction2();
Upvotes: 6