Vue 3:如何使用组合 api 正确更新组件道具值?
Vue 3: How to update component props value correctly using composition api?
我喜欢这个组件:
<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
方法更新属性 coords
值,但我收到错误消息:
Uncaught TypeError: Cannot set properties of undefined (setting
'coords')
在我的情况下如何正确更新道具值?
道具是只读的:
https://v3.vuejs.org/guide/component-props.html#one-way-data-flow
如果你想对 props 进行两种方式的绑定,你需要实现 v-model 模式:
https://v3.vuejs.org/guide/migration/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>
我喜欢这个组件:
<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
方法更新属性 coords
值,但我收到错误消息:
Uncaught TypeError: Cannot set properties of undefined (setting 'coords')
在我的情况下如何正确更新道具值?
道具是只读的:
https://v3.vuejs.org/guide/component-props.html#one-way-data-flow
如果你想对 props 进行两种方式的绑定,你需要实现 v-model 模式:
https://v3.vuejs.org/guide/migration/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>