Vue 3:如何使用组合 API 正确更新组件 props 值?

And*_*ter 9 javascript vue.js vue-component vue-props vuejs3

我有这样的组件:

<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>
Run Code Online (Sandbox Code Playgroud)

我尝试使用方法更新 propcoordsupdateCoords,但收到错误消息:

未捕获的类型错误:无法设置未定义的属性(设置“坐标”)

在我的情况下如何正确更新 props 值?

Tho*_*mas 13

道具是只读的: https:
//v3.vuejs.org/guide/component-props.html#one-way-data-flow

如果您想对道具进行两种方式绑定,则需要实现 v-model 模式: https:
//v3-migration.vuejs.org/writing-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>
Run Code Online (Sandbox Code Playgroud)