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?
JavaScript
x
22
22
1
<script>
2
3
export default {
4
setup() {
5
const state = reactive([])
6
7
function myFunction() {
8
state.push({'item':1})
9
console.log(state); // state change
10
}
11
12
watchEffect(() => {
13
console.log(state) // state doesn't change
14
})
15
16
return {
17
myFunction
18
}
19
}
20
}
21
22
</script>
JavaScript
1
3
1
<template>
2
<button @click="myFunction()">Click Here</button>
3
</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…
JavaScript
1
21
21
1
const app = Vue.createApp({
2
setup() {
3
const state = Vue.reactive([])
4
5
function myFunction() {
6
state.push({
7
'item': 1
8
})
9
console.log(state); // state change
10
}
11
12
Vue.watchEffect(() => {
13
console.log(state) // state doesn't change
14
})
15
16
return {
17
myFunction
18
}
19
}
20
})
21
app.mount("#app")
JavaScript
1
4
1
<script src="https://cdn.jsdelivr.net/npm/vue@3.2.26/dist/vue.global.min.js"></script>
2
<div id="app">
3
<button @click="myFunction()">Click Here</button>
4
</div>