Search code examples
javascriptvue.jsvue-componentvuejs3vue-props

Vue 3: How to update component props value correctly using composition api?


I have like this component:

<template>
  <div>
    <p>Current coords: <strong>{{ coords }}</strong></p>
    <button type="button" @click="updateCoords">
  </div>
</template>
<script>
export default {
  props: {
    coords: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    const updateCoords = () => {
      props.coords = [38.561785, -121.449756]
      // props.coords.value = [38.561785, -121.449756]
    }
    return { updateCoords }
  },
}
</script>

I tried update prop coords value with updateCoords method but I get error message:

Uncaught TypeError: Cannot set properties of undefined (setting 'coords')

How I can correctly update props value in my case?


Solution

  • Props are readonly:
    https://v3.vuejs.org/guide/component-props.html#one-way-data-flow

    If you want to have two way binding for props, you'll need to implement the v-model pattern:
    https://v3-migration.vuejs.org/breaking-changes/v-model.html#_3-x-syntax

    <template>
      <div>
        <p>Current coords: <strong>{{ coords }}</strong></p>
        <button type="button" @click="updateCoords">
      </div>
    </template>
    <script>
    export default {
      props: {
        modelValue: {
          type: Array,
          required: true
        }
      },
      emits: ['update:modelValue'],
      setup(props, {emit}) {
        const updateCoords = () => {
            emit('update:modelValue', [38.561785, -121.449756])
        }
        return { updateCoords }
      },
    }
    </script>