Vue Setup脚本渲染计算属性时出现变量未找到的问题
Vue SFC计算属性中找不到props变量的原因及解决方法
问题描述
我正在迁移至Vue单文件组件(Vue SFC),在使用计算属性时遇到问题。我编写代码希望实现点击顶部标题行切换底部内容行的显示状态,使用computed定义markedContent时出现ReferenceError找不到content变量,但直接在模板中调用marked.parse(content)却运行正常,现询问该问题的原因及Setup脚本中计算属性的正确用法。
代码示例
<!-- components/Note.vue --> <script setup> import { marked } from "marked"; import { ref, computed } from "vue"; const props = defineProps({ id: Number, title: String, create: String, content: String }); const showContent = ref(false); const elContent = ref(null); const scrollHeight = computed(() => { return elContent.value.scrollHeight + "px"; }); const markedContent = computed(() => { return marked.parse(content.value); }) </script> <template> <div class="row" @click="showContent=!showContent"> <div class="col-9">{{ title }}</div> <div class="col-3">{{ create }}</div> </div> <div class="row" :style="{height:showContent?scrollHeight:0}" ref="elContent"> <div class="col">{{ markedContent }}</div> </div> </template>
错误信息
[Vue warn]: Unhandled error during execution of render function (9) " " " at <Note" "id=27" "title=\"1Lorem Ipsum\"" " ..." ">" " " " at <App>" [Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core (9) " " " at <Note" "id=27" "title=\"1Lorem Ipsum\"" " ..." ">" " " " at <App>" Unhandled Promise Rejection: ReferenceError: Can't find variable: content
正常运行的模板写法
<!-- This is fine --> <div class="row" :style="{height:showContent?scrollHeight:0}" ref="elContent"> <div class="col">{{ marked.parse(content) }}</div> </div>
问题原因及解决方法
原因
在<script setup>中,defineProps返回的props对象是所有传入属性的集合。模板中可以直接使用content是因为Vue对模板做了自动代理,允许直接访问props的属性;但在脚本内部,必须通过props对象来访问对应的属性,直接写content会被视为未定义的变量,而且content不是ref类型,不需要加.value。
正确用法
修改计算属性的代码,通过props.content访问传入的内容:
const markedContent = computed(() => { return marked.parse(props.content); })
如果content可能为空值,建议添加空值判断避免解析报错:
const markedContent = computed(() => { return props.content ? marked.parse(props.content) : ''; })
内容的提问来源于stack exchange,提问作者Ezon Zhao
相关产品推荐
相关产品推荐

