vue 3 reactive custom class object with methods

Viewed 769

Let's say in my component I have simple computed array of items, all of which are type of custom class Item. Item is an object of a custom class with private methods.

// items is a computed array
const items = computed(() => [new Item("first"), new Item("second"),...]);

// item class
class Item{

   constructor(itemName){
       this.itemName = itemName;
       this.inStock = this.#itemInStock(itemName);
       // other properties initialized by some other private methods
     }

   #itemInStock(item){
         return items.indexOf(item) !== -1;
     }

}

Now I have been reading about reactivity, here, and if I understood vue uses Proxies to catch attempt to read property and Reflects to use binding, but will it catch methods as well? Can I use private methods in class instance and then use that class instance in template? Private methods should not be accessed directly e.g. Item.itemInStock should fire error.

Please note that I don't intent to use any of my methods directly in template nor anywhere in application (that is why I made them private)

1 Answers

you can use method reactive and toRefs.

first, you can import this methode.

import { reactive, toRefs } from 'vue

second, you change on your computed

const items = computed(() => reactive[new Item("first"), new Item("second"),...]);

and you change return with

return toRefs(items.indexOf(item))

if your data is object, you should add spread in your return

return ...toRefs(items.indexOf(item))

Related