Vue composition api is not updating bound value to text field

Viewed 5065

I am updating an attribute of an object after initialization.

My dumbed-down component looks like this:

<template lang="pug">
  div
    v-text-field(v-model="object.name")
    v-text-field(v-model="object.vpnPort")
</template>

<script>
import { ref } from '@vue/composition-api'
export default {
  setup(props, { root }) {
    const object = ref({})

    getNextPort().then(response => (object.value.vpnPort = response.data))

    return { object }
  }
}
</script>

In this example, getNextPort is an API call that returns a number. For some reason, the v-text-field is not updated. I do not see the value in the input field. When I console.log the object after the getNextPort call it shows:

{"vpnPort":10001}

Which is the expected result. I also tried:

  • $nextTick
  • onMounted
  • $forceUpdate

But when I start typing in the name field the vpnPort doest get updated!

Does anybody know why the result is not shown in the v-text-field?

2 Answers

You should initialize your object data with empty fields like :

const object = ref({
  name:'',
  vpnPort:null
 })

for reactive objects, you should use reactive

const object = reactive({
  name: '',
  vpnPort: null
})

change

object.value.vpnPort = response.data

to

object.vpnPort = response.data

check out https://composition-api.vuejs.org/#ref-vs-reactive for more info

Related