setup should support class prototype method in template
What problem does this feature solve?
What does the proposed API look like?
in template should can use setup function return object prototype method
- return new CountService();
+ return { cs: new CountService() };
return { cs: new CountService() };
<p>{{ cs.count.value }}</p>
<button @click="cs.add">+</button>
This is a problem with destructuring class methods more than it is with Vue. When destructuring a class prototype method, it loses its this
context.
class CountService {
count = ref(0)
add() {
this.count.value++
}
}
const counter = new CountService()
const add = counter.add
add()
console.log(counter.count.value) // => 0
I'm not convinced it should be Vue's job to treat a class specially when using it for as setup()
's return object, as you would have the above problem in different other usages as well, for example with provide
(which we can't solve):
import { provide } from 'vue'
const counter = new CountService()
provide('add', counter.add)
Rather, you as the author/user of this class are repsonsible to take care of this, by either manually binding the method to the class' this
, or using arrow functions (example for the latter below):
@LinusBorg i want to use decorator in class prototype method. so i can use autobind
to bind this to prototype methods