javascript - Vue 3:如何使用组合 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>
我尝试coords
使用方法更新道具值,updateCoords
但收到错误消息:
未捕获的类型错误:无法设置未定义的属性(设置“坐标”)
在我的情况下,如何正确更新道具值?
解决方案
道具是只读的:
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>
推荐阅读
- java - Elasticsearch:使用 Java 客户端查找给定索引的所有映射类型
- php - 如何在 composer 和 /vendor/autoload.php 之前加载文件?
- java - View、Viewgroup、onClick、getChildAt问题
- android - 如何创建一个可以在一段时间后自行卸载的应用程序
- python - 为什么我在使用 python fire 时总是打印类型信息?
- python - 基于if语句的for循环,错误信息= Series的真值不明确
- javascript - 加载/显示最后搜索值的页面
- nginx - “/usr/share/nginx/html/AppzillonServer”失败(2:没有这样的文件或目录)
- html - Markdown 中“隐藏”属性的替代方法是什么?
- php - Nginx - 无法上传大于 10Kb 的文件