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

u4dcyp6a  于 7个月前  发布在  Vue.js
关注(0)|答案(2)|浏览(138)

我喜欢这个组件:

<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>

字符串
我尝试使用updateCoords方法更新prop coords值,但收到错误消息:
未捕获的TypeError:无法设置undefined的属性(正在设置“coords”)
我如何正确地更新 prop 值在我的情况下?

vi4fp9gy

vi4fp9gy1#

prop 是只读的:
https://v3.vuejs.org/guide/component-props.html#one-way-data-flow
如果你想拥有props的双向绑定,你需要实现v-model模式:
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>

字符串

9vw9lbht

9vw9lbht2#

如果你想更新props并在vue 3中更改它,你必须根据你的代码修改你的代码,如下所示:

<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>

字符串
要点是在父组件中的组件中编写prop,如下所示:

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

相关问题