Separating vuex stores for dynamically created components

后端 未结 2 1084
广开言路
广开言路 2021-01-31 16:19

This was the question got me stuck for a little bit. Unfortunately, I coudn\'t find answer here (asking also didn\'t help). So after doing some research and asking here

2条回答
  •  佛祖请我去吃肉
    2021-01-31 17:06

    Hi and thank you for posting your question and your solution.

    I started learning Vuex couple days ago and came across a similar problem. I've checked your solution and came up with mine which doesn't require registering new modules. I find it to be quite an overkill and to be honest I don't understand why you do it. There is always a possibility I've misunderstood the problem.

    I've created a copy of your markup with a few differences for clarity and demonstration purposes.

    I've got:

    1. JobList.vue - main custom component
    2. Job.vue - job-list child custom component
    3. jobs.js - vuex store module file

    JobList.vue (which is responsible for wrapping the job(s) list items)

    
    
    
    

    The Job

    
    
    
    

    And finally the jobs.js Vuex module file:

    export default {
        state: {
            jobs: [
                {
                    id: 1,
                    name: 'light',
                    active: false
                },
                {
                    id: 2,
                    name: 'medium',
                    active: false
                },
                {
                    id: 3,
                    name: 'heavy',
                    active: false
                }
            ]
        },
    
        actions: { //methods
            newJob(context, jobName) {
                context.state.jobs.push({
                    id: context.getters.newJobId,
                    name: jobName,
                    active: false
                });
            },
            toggleJobState(context, id) {
                context.state.jobs.forEach((job) => {
                    if(job.id === id) { job.active = !job.active; }
                })
            }
        },
    
        getters: { //computed properties
            newJobId(state) { return state.jobs.length + 1; }
        }
    }
    

    It's possible to add new jobs to the store and as the "active" property suggest, you can control every single individual job without the need for a new custom vuex module.

提交回复
热议问题