javascriptvue.jsvue-composition-apipiniavue-props

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


Solution

  • I would not suggest to use the Vue predefined names, like props to name variables/props/events in Vue, since you will possibly have a conflict and it will be hard to clarify what's going on.

    So, I have changed props: ['props'] to props: ['data']

    Here is a very basic example with Pinia

    const { createApp } = Vue
    const { createPinia, defineStore, storeToRefs } = Pinia
    
    const useErrorsStore = defineStore('ErrorsStore', 
    {
      state: () => {
        return {
          List: []
        }
      },
      actions: {
       add(data) {
          data && this.$state.List.unshift(data) 
        }
      }  
    })
    
    const MyComp = {
      props: ['data'],
      setup(props) {
        const store = useErrorsStore()        
        console.log(props);
        store.add(props.data);    
        return {    
          store
        }
      },
      template: '{{store.List}}' 
    }
    
    const App = {
      components: { MyComp },
      setup() {
        const store = useErrorsStore()
        return {
          store
        }
      }
    }
    
    const app = createApp(App)
    const pinia = createPinia()
    app.use(pinia)
    app.mount('#app')
    #app { line-height: 1.75; }
    [v-cloak] { display: none; }
    <div id="app">
      MyComp: <my-comp :data="{ item: 1 }"></my-comp>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/[email protected]/lib/index.iife.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/pinia.iife.js"></script>