Home > Software engineering >  Vue 3 composition API: can not access reactive array value programmatically, only in template
Vue 3 composition API: can not access reactive array value programmatically, only in template

Time:01-24

In a component, i defined a reactive constant (isn't that paradox?) like this:

const form = reactive({
    name: null,
    fruits: new Array(),
})

The value for name is set via a text input field. The value for fruits is set via a group of checkboxes.

when i want to get the values of each programmatically using this function:

const makeObj = () => {
    console.log("form.name", form.name)
    console.log("form.fruits", form.fruits)
}

... i can only access form.name, but form.fruitsreturns some Proxy object:

console.log

BUT: I can access the elements of the array directly with form.fruits[0]returning the first item, e.g. Banana.

Question: How can i access the array value of form.fruits? Do i have to convert the reactive array form.fruits to a "normal" array somehow?

Thanks for your help!

CodePudding user response:

Proxy is Vue’s reactivity system that allows to track dependencies and changes to the array. Pretend it isn't there :) You can do with it everything you can with plain array.

const { reactive, onMounted } = Vue
const app = Vue.createApp({
  setup() {
    const form = reactive({
      name: null,
      fruits: new Array()
    })
    const makeObj = () => {
      form.name = 'aa'
      form.fruits = [1,2,3]
      console.log("form.name", form.name)
      console.log("form.fruits", form.fruits)
    }
    onMounted(() => {
      makeObj()
    })
    return { form }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  {{ form }}
</div>

  • Related