Home > Mobile >  What is the benefit of using a ref on a service?
What is the benefit of using a ref on a service?

Time:11-04

Consider these two approaches of calling a service in a Vue 3 Component (composition API)

Direct usage:

import productService from '@/services/product.service';
productService.getProducts().then(data => products.value = data);

Wrapped in a ref:

import productService from '@/services/product.service';
const productService = ref(new ProductService());
productService.value.getProducts().then(data => products.value = data);

I stumbled upon the second variant in the docs of PrimeVue

Is there any benefit of using a ref over a direct usage?

CodePudding user response:

Ref object is used for the cases when a value is reassigned in other place and can be read in another place, the pattern makes use of the fact that objects are passed by reference rather than by value in JavaScript.

Since productService value is never changed, there's no benefit from using a ref.

  • Related