This question really had me stumped for a while. I couldn't find the answer here (asking around didn't help either). However, after conducting some research and seeking advice from various sources, I believe I have finally arrived at a solution to this problem.
If you have a question that you already know the answer to, and you would like to share that knowledge publicly so that others (including yourself) can benefit from it later on.
Admittedly, my solution may not be perfect - in fact, I am well aware that it is not. That's precisely why I'm sharing it here - to receive feedback and improve upon it.
It's important to note that I did not utilize any actions in this example. The concept remains the same.
Let's start by defining the issue at hand:
Imagine we have a file called App.vue
which dynamically generates its own local component named Hello
.
<template>
<div id="app">
<div>
<hello v-for="i in jobs" :key="i" :id="i"></hello>
<button @click="addJob">New</button>
</div>
</div>
</template>
<script>
import Hello from './components/Hello'
export default {
components: {
Hello
}...
store.js
export const store = new Vuex.Store({
state: {
jobs: []
}
})
We are using the v-for
directive to generate components by looping through an array called jobs
. Our current store
only consists of a single state
with an empty array.
The New
button should perform two tasks:
1) create a new component Hello
, essentially adding an element to the jobs
array (let them be numbers), which will serve as the key
and id
for the <hello>
component, and then passed as props
to the local component.
2) generate individual stores - known as modules - to contain data specific to each newly created component.
Hello.vue
<template>
<div>
<input type="number" :value="count">
<button @click="updateCountPlus">+1</button>
</div>
</template>
export default {
props: ['id']
}
A straightforward component featuring an input field and a button that increments the count by 1.
Our objective is to achieve something along these lines: https://i.sstatic.net/6MA1X.jpg