Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use stores and props in onMounted Vue

I’m new in Vue Composition API and some functions as defineProps are not available. So, I have a following problem: from parent component I’ve got props and want to store in "Pinia" storage after a few calculations. How can I do it?

export default defineComponent({
  props: ['props'],
  setup() {
    const errorsStore = useErrorsStore();
   
    onMounted(() => {
      const status = (props) => {
        console.log(props);
        errorsStore.List.unshift(props);
        setInterval(status, 10000)
      }
      status(props);
    });
    return {
      errorsStore,
    };
  },
});

I’ll be glad, if you answer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import { defineComponent, onMounted, toRefs } from 'vue';
import { useErrorsStore } from './store';

export default defineComponent({
  props: ['props'],
  setup(props) {
    const { props: reactiveProps } = toRefs(props);
    const errorsStore = useErrorsStore();
   
    onMounted(() => {
      const status = () => {
        console.log(reactiveProps.value);
        errorsStore.List.unshift(reactiveProps.value);
      };
      setInterval(status, 10000);
    });
    
    return {
      errorsStore,
    };
  },
});

In this code, we use toRefs(props) to create a reactive object called reactiveProps that contains the props. We can then access the prop values using reactiveProps.value.

Also, note that we removed the (props) parameter from the status function because props is already available in the setup function scope.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading