I have wasted my time for this. I am using Vue 3 options API previously and I am trying change to compostion API. I want to push an object to array but the state doesn’t update value, why this happen?
<script> export default { setup() { const state = reactive([]) function myFunction() { state.push({'item':1}) console.log(state); // state change } watchEffect(() => { console.log(state) // state doesn't change }) return { myFunction } } } </script>
<template> <button @click="myFunction()">Click Here</button> </template>
Advertisement
Answer
You have a syntax error in your code. The function declaration should be as function myFunction() { ...
instead of function myFunction {...
Always check the browser console for any error first before asking on internet…
const app = Vue.createApp({ setup() { const state = Vue.reactive([]) function myFunction() { state.push({ 'item': 1 }) console.log(state); // state change } Vue.watchEffect(() => { console.log(state) // state doesn't change }) return { myFunction } } }) app.mount("#app")
<script src="https://cdn.jsdelivr.net/npm/vue@3.2.26/dist/vue.global.min.js"></script> <div id="app"> <button @click="myFunction()">Click Here</button> </div>