道具是只读的:
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>
如果你想更新
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"/>