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

问题描述 投票:0回答:2
javascript vue.js vue-component vuejs3 vue-props
2个回答
12
投票

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

如果你想要有两种方式绑定 props,你需要实现 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>

0
投票

如果你想更新

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>

但是要点是在父组件中的组件中调整你的道具,如下所示:

//parent component 
<child-component v-model:component-props-name="value"/>
© www.soinside.com 2019 - 2024. All rights reserved.