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,
};
},
};
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
};
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With