Search code examples
vue-componentvuejs3vue-composition-apivue-reactivityprimevue

Does it make sense using Vue 3 reactivity on a service?


I have found following DataTable code snippet by PrimeVue, that uses the new Compositon API

<script>
import { ref, onMounted } from 'vue';
import ProductService from './service/ProductService';

export default {
    setup() {
        onMounted(() => {
            productService.value.getProductsSmall().then(data => products.value = data);
        })

        const products = ref();
        const productService = ref(new ProductService());
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^    
        return { products, productService }
    }
}
</script>

Does it make any sense to ref() the ProductService?
I guess it does not. Am I wrong?


Solution

  • I believe you are correct, the assignment to ref is unnecessary.

    I thought that might have been added for consistence with the options API:

    import ProductService from './service/ProductService';
    
    export default {
        data() {
            return {
                products: null
            }
        },
        productService: null,
        created() {
            this.productService = new ProductService();
        },
        mounted() {
            this.productService.getProductsSmall().then(data => this.products = data);
        }
    }
    

    However the productService is not part of the data object, so it is not reactive, and because it is a service that doesn't hold state it doesn't need to be.