Exploring the functionalities of stores and props within the Vue onMounted lifecycle method

As a newcomer to the Vue Composition API, I've run into some issues with functions like defineProps not being available. My current predicament involves receiving props from a parent component and wanting to store them in the "Pinia" storage after a series of calculations. Can anyone provide guidance on how to achieve this?

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

Your assistance on this matter would be greatly appreciated.

Answer №1

Avoid using Vue's predefined names like props for naming variables/props/events in Vue to prevent conflicts and confusion.

For example, I changed props: ['props'] to props: ['data']

Take a look at this simple example using 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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a0a3b3fbb2b3bbbf96e6f8e7e5f8e7e7">[email protected]</a>/lib/index.iife.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e0f9fef9f1d0a2bea0bea3a0">[email protected]</a>/dist/pinia.iife.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on effectively clearing the context and canvas in three.js

We are currently developing an application that is also compatible with use on iPads, utilizing three.js version r100. Within our application, we have a "main" component and various "popups", each equipped with its own canvas, scene, and renderer. The "ma ...

saving numeric values and text to a document using node.js

In my node.js application, I am working with files to read and write numbers and strings. Currently, I am using fs.writeFileSync(myPath, value); where the value can be either a number or a string. When I try to read the file using fs.readFileSync(myPa ...

Having trouble executing node commands in the terminal

After launching the terminal on my Mac, I made sure to confirm that Node was installed by running the command: node -v v14.17.5 Next, when attempting to open a file I had created called index.html from Visual Studio Code, I encountered an error message in ...

When I bundle my project with Vite, the Styles seem to have disappeared

My styles seem to be missing when I compile my app in IIFE format. This includes the style tag in SFC and CSS imported to app.ts. I'm not sure if it's a Vite or RollUp issue... The styles work fine with vite serve, but not with vite build. I no ...

I have created a textbox with a button, but I am unsure of how to delete it

var emailFields = document.getElementById('emails'), addLinkButton = document.createElement('a'), fieldTemplate = emailFields.getElementsByTagName('div'), currentFieldCount = fieldTemplate.length, maxFields ...

obtain data in JSON format from a Node.js server and display it on an HTML

I am currently working on a feature that involves sending an AJAX request to the server and receiving the output of a MySQL query on the page http://localhost:3000/result.html upon clicking a button. <body> <form action="/setLocation" method=" ...

The concept of position() is often mistaken for a function

I am currently developing a slider and have included the code below: $(document).ready(function() { // MAKE SLIDER WIDTH EQUAL TO ALL SLIDES WIDTH var totalWidth = 0; $('.slide').each(function() { totalWidth = totalWi ...

Exploring the possibilities of integrating vuex into Vue 3

In the past year, I dedicated time to learning Vue 2 and found it very enjoyable. However, I didn't proceed with a project at that time. Now, I have the opportunity to start a new project and would like to utilize Vue 3 along with the composition API, ...

I'm looking for help on creating a three-column table using javascript/jquery. The table should display Product, Price, and Discount (which is calculated at 20%). Can anyone

Check out this code snippet. var items = ["Laptop", "Tablet", "Smartphone", "Headphones", "Camera"]; var costs = [599.99, 299.99, 799.99, 149.99, 499.99]; displayItems = ""; totalCost = 0; for (var j = 0; j < items.length; j++) { displayItems += " ...

The latest version of Next.js, 11.1.0, does not support monitoring for code changes within the node

In the latest version of Nextjs (11.1.0), there seems to be an issue where code changes in the `node_modules` directory are not being watched, unlike in the previous version (10.2.1). While working on a project with Nextjs 11.1.0, I have tried explicitly ...

Is it beneficial to rotate an image before presenting it?

I am looking for a way to display a landscape image in portrait orientation within a 2-panel view without altering the original file. The challenge I am facing is that the image size is set before rotation, causing spacing issues with DOM elements. Is ther ...

The process of loading an image becomes stuck once the submit button is pressed

I have multiple JSP pages where I use an ajax call to submit data. On these pages, I am able to display a loading image before the ajax call and hide it once the call is complete, which works perfectly. $(document).ajaxComplete(function() { $("#loadi ...

"Creating dynamic web apps with the powerful duo of Meteor and Zurb

Just starting out with programming and currently working on a new web application using Meteor and AngularJS. I would like to incorporate the elements/css from 'Zurb Foundation For Apps' into my project... I am familiar with including Bootstrap ...

Is there a way to execute two files concurrently in JavaScript using node.js?

I'm a beginner in the world of Javascript and Node.js, and I've encountered some issues while trying to test code I recently wrote. Specifically, I am attempting to test the code within a file named "compareCrowe.js" using another file named "tes ...

The Recharts Line chart fails to display newly added data points when data is updated

My app features a straightforward tool that enables users to monitor their weight changes over time. Despite successfully receiving new data in the props, the chart does not update and display the new point. Recharts Component: import React from 'rea ...

"Enhance Your Website with Javascript: Combining and Incorpor

I'm struggling to assign the selected attribute to the option value that is already rendered within the object. However, despite the values being equal, the selected attribute is not being added. Could this issue be related to the appending process? ...

Preserve page configurations upon page refresh

I'm currently in the process of creating a 'user settings' form. Each list item represents a different section, such as Updating username, Updating email, and Changing password. It looks something like this: <li> <header>Ti ...

Alignment of content layout across two wrapper elements

My goal is to achieve a specific layout where each pair of cards in a two-column layout is aligned based on the card with the largest content. Both cards share the same content layout and CSS. If you have any ideas or implementations that could help me ac ...

Steer clear of receiving null values from asynchronous requests running in the background

When a user logs in, I have a request that retrieves a large dataset which takes around 15 seconds to return. My goal is to make this request upon login so that when the user navigates to the page where this data is loaded, they can either see it instantly ...

Utilize the keyboard's vertical arrows to adjust values as needed

Implement the functionality to increase and decrease the value in a label or p tags using the onkeydown and onkeyup events, without requiring a textbox input. I have come across numerous examples, but they all rely on textboxes. I am looking for a soluti ...