Subscribe on changes!

setup should support class prototype method in template

avatar
Aug 17th 2023
- return new CountService();
+ return { cs: new CountService() };
return { cs: new CountService() };
<p>{{ cs.count.value }}</p>
<button @click="cs.add">+</button>
avatar
Aug 18th 2023

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):

https://play.vuejs.org/#eNp9kstu2zAQRX+F4CYO7EhB05UhG2nTLNpFWzRdcqNQY5sJNSTIoWNA0L93REFqnD4AASLvXA7OPDr5wfvimECuZRV1MJ62Ck3rXSDRiQZ2BuHO8R0BaSUC7EQvdsG14oJfXShUqG0do7hzCekBwtFoEJ1CIfSgiM3wZnF9OTiFqJuGlcWl2GxHkxB0MLHI3uJY2wTL5aD3CvlTCKeMwiB1svn/GmiRc0Sg5NfnWQNrAQXCyxnZgjnG5HyoyrlivhC03tYEfBOi8tuuy1B9X5V+1B4TkUNxq63RzxsluRglt8uqHANsqso5i1xJitrhzuyLp+iQG5zRlNRMbyyEb56Mw6jkeoLmlNa6ly9Zo5BgNen6APr5L/pTPA2akt8DRC4RlJxjVIc90Bi+f/gKJz7PwdY1ybL7P8EfEJ1NA+No+5iwYexXvkz7OS+Lwf3PeH8iwDgVdQbKc4RgWp5ZbT+BdqEmF2ZbHkr2KslrNcz3Xx36XdVNcTMNk5s97uxVW/s37R4Db9qcyD0abK6aCWUs8UDk47osdYOcpQFrjqFAoBJ9W/756PZd8b64LpcQWyVnlv4XTBYe1Q==

avatar
Aug 18th 2023

That's also a solution, great 👍

avatar
Aug 18th 2023

i think setup function return object should can get prototype method in template. i think this is a intuitive feature