11

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?

2 Answers 2

14

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>
Sign up to request clarification or add additional context in comments.

Comments

0

if you want to update props and change it in vue 3 you must right your code according to your code like this:

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

but the main point is to write your prop in a component in the parent component like this:

//parent component 
<child-component v-model:component-props-name="value"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.