[Vuejs]-Vue Js should I be using Vuex for this?

1đź‘Ť

âś…

To be honest, if you have two components in a hierarchy then this doesn’t really need Vuex. You just need to think about your components and how they interact.

If a PlayerCard component has a child ColorPicker component, then you’re right that the ColorPicker component should emit an event with the picked colour. The PlayerCard component can just listen on that event and set whatever binding it needs to:

<!-- /components/PlayerCard.vue -->
<template>
    <div v-bind:style="{ 'background-color': this.backgroundColor }">
        <color-picker v-bind:value="backgroundColor" v-on:input="updateBackgroundColor" />
    </div>
</template>

<script>
    export default {
        components: {
            ColorPicker
        },
        data() {
            return {
                backgroundColor: '#000' // default
            };
        },
        methods: {
            updateBackgroundColor(event) {
                this.backgroundColor = event.target.value;
            }
        }
    }
</script>

<!-- /components/ColorPicker.vue -->
<template>
    <div>
        <input type="color" v-on:input="onInput" v-bind:value="value" />
    </div>
</template>

<script>
    export default {
        methods: {
            onInput(event) {
                this.$emit('input', event);
            }
        },
        props: {
            value: {
                required: true,
                type: String
            }
        }
    }
</script>

Here we have two components. When the input in the ColorPicker changes its value, it passes the input event up to the PlayerCard component, that then sets the background colour in response.

The ColorPicker component also remains “dumb”, in that it doesn’t know anything about the components it’s being used in—it literally just allows a user to pick a colour. The parent component listens on the input event and does something in response. So this makes the ColorPicker component re-usable for picking other colours you may need to for your PlayerCard component, i.e. text colour.

There’s nothing here really that Vuex will solve that properly-written Vue components can’t accomplish. Vuex will just make it easier to code around problems, rather than solve any. But Vuex does have a place in larger applications.

👤Martin Bean

0đź‘Ť

I noticed that your event listener is @colorChosen (in your PersonCard.vue), but you are emiting “newColor”, change that to @newColor (in your PersonCard.vue). See if that helps.

<ColorPick @newColor="newColor"></ColorPick>

And yes Vuex can make passing bits of state from component to component a breeze. As your app grows and expands, it can get a little tricky to keep track of all your emits.

👤Suoakira

Leave a comment