Search code examples
vue.jsquasar

Dynamically update props


As simplified below, my app has a template with a custom component.

The data is passed from Template A to custom component as props (":list")

Template A:

<template>
...
<custom-component     
    v-for="list in listGroup" 
    :key="list.id_list" 
    :list="list"                      
/>
</template>

<script>
    export default {        
        data() {
            return {
             listGroup: []
            };
        },
        components: {
            'custom-component':require("...").default
        }
</script>

The custom component

<template>
...
</template>

<script>
    export default {
        props:["list];
        ...
    }
</script>

Problem to solve:

A new item is added to the list sent as props.

I need the list (:list="list") to be dynamically updated so that the props in the custom component automatically reflect that update.

Thanks.


Solution

  • There are two ways to achieve that one way is to use a state management library(Vuex is recommended) the other is to use events.

    Here is an example of using events:

    create a file event-bus.js with the following content

    import Vue from "vue";
    export const EventBus = new Vue();
    

    then in your component where you want to update list use this EventBus.$emit('eventName', data);

    remember to import event-bus file

    the listen to the event in the other component

    EventBus.$on('eventName', function (details) {
        //update list here
    });