Vue3中如何通过Composition API将props绑定为本地属性?
Vue 3 中将单向 Props 转为本地变量的正确实现
在 <script setup> 语法中,defineProps 调用后会返回当前组件的 props 对象,你之前的写法没有接收这个返回值,所以才会出现 props 未定义的错误。以下是几种正确的实现方式:
基础写法:接收 props 对象
直接接收 defineProps 的返回值,再用它初始化本地响应式变量:
<script setup> import { ref } from 'vue'; // 接收 defineProps 返回的 props 对象 const props = defineProps({ initialCounter: Number }) // 用 props 的值初始化本地响应式变量 const counter = ref(props.initialCounter) </script>
解构写法(保留响应性)
如果想解构 props 使用,由于 props 是响应式对象,直接解构会丢失响应性,需要借助 toRefs 处理:
<script setup> import { ref, toRefs } from 'vue'; const props = defineProps({ initialCounter: Number }) // 用 toRefs 解构,确保每个属性仍保持响应性 const { initialCounter } = toRefs(props) const counter = ref(initialCounter.value) </script>
同步 props 更新到本地变量
如果需要在 initialCounter 变化时自动更新本地的 counter,可以添加监听逻辑:
<script setup> import { ref, watch } from 'vue'; const props = defineProps({ initialCounter: Number }) const counter = ref(props.initialCounter) // 监听 props 的变化,同步更新本地变量 watch(() => props.initialCounter, (newValue) => { counter.value = newValue }) </script>
内容的提问来源于stack exchange,提问作者nowox
相关产品推荐
相关产品推荐

