successdav's avatar

I learned this code is supposed to re render vue component

this.$set(this.itemsTwo, 'root', item);

But its not working

Full Code

data() {
            return { 
                itemsTwo: {},
                dataSet: false,
            };
      },

add(item) {
                if (this.itemsTwo.hasOwnProperty('root')) {
                    this.itemsTwo['root'].push(item);
                }else {
                    this.$set(this.itemsTwo, 'root', item);
                }
            },
0 likes
2 replies
successdav's avatar

My idea now is to rebuild the items array, so it can trigger the vue reactivity, Anyway around this?

nolros's avatar
nolros
Best Answer
Level 23

this should work for you. Use computed props for reactivity.

<template>
    <div v-if="hasData">
        <ul>
            <li v-for="(item,idx) in getItems" 
                :key="item.id">
                {{ item.value }}
            </li>
        </ul>
    </div>
</template>


    export default {
        name: "VueComponent",
        data() {
            return {
                itemsTwo: [], // change to array
            };
        },
        methods: {
            add(item, key = 'post') {
                this.itemsTwo[key].push(item);
            },
        },
        computed: {
            getItems() {
                return this.itemsTwo;
            },
            hasData() {
                return this.itemsTwo.length > 0;
            },
        },
    }

Please or to participate in this conversation.