Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - composition API Array inside reactive is not updating in the DOM

I have an Array of posts inside reactive() and I want it to be updated onMounted.

How can I do this?

TEMPLATE:

<q-card>
  <board-item-list :items="items" v-if="items.length" />
  <board-empty v-else />
</q-card>

SCRIPT

import { reactive, onMounted } from "vue";
import { posts } from "./fake-data.js";
export default {
  setup() {
    let items = reactive([]);
    ...
    onMounted(() => {
      // to fill the items with posts.
      items.values = posts; // I tried this not working
      items = posts; //I tried this not working
      console.log(items);
    });
    ...
    return {
      ...
      items,
    };
  },
};
like image 611
Evan Avatar asked Sep 16 '25 02:09

Evan


1 Answers

Try to use ref instead of reactive or define items as nested field in a reactive state like :

import { reactive, onMounted } from "vue";
import { posts } from "./fake-data.js";
export default {
  setup() {
    let state= reactive({items:[]});
    ...
    onMounted(() => {
     
      state.items = posts; 
      console.log(state.items);
    });
    ...
    return {
      ...
      state,
    };
  },
};

in template :

<q-card>
  <board-item-list :items="state.items" v-if="state.items.length" />
  <board-empty v-else />
</q-card>

if you want to get rid of state in the template you could use toRefs:

import { reactive, onMounted,toRefs } from "vue";
import { posts } from "./fake-data.js";
export default {
  setup() {
    let state= reactive({items:[]});
    ...
    onMounted(() => {
     
      state.items = posts; 
      console.log(state.items);
    });
    ...
    return {
      ...toRefs(state),//you should keep the 3 dots
    };
  },
};

like image 162
Boussadjra Brahim Avatar answered Sep 18 '25 16:09

Boussadjra Brahim