Vue 3中setup函数使用this赋值报Cannot set property of undefined错误原因
报错原因
- 核心触发原因是 Vue 3 的
setup函数执行时机早于组件实例初始化,setup内部没有绑定组件实例this,你访问this得到的是undefined,尝试给undefined的codes属性赋值就触发了对应类型错误。 - 额外存在语法结构问题:你的代码缺失
<script>起始标签,export default代码块必须包裹在完整的<script>标签对内才能正常解析。
解决方案
方案1:沿用选项式API写法,将赋值逻辑迁移到选项式生命周期中
如果要保留data选项的写法,把赋值逻辑从setup移到mounted等选项式生命周期钩子中即可,此时this指向正常的组件实例:
<template> <p>{{ codes }}</p> </template> <script> export default { data() { return { codes: 'test' } }, name: 'Functions', props: { msg: String }, mounted() { this.codes = 'does it work?'; } } </script> <style> </style>
方案2:遵循组合式API规范,在setup内直接定义响应式数据
如果要使用setup,无需再搭配data选项,直接在setup内定义响应式变量并返回即可,不需要用到this:
<template> <p>{{ codes }}</p> </template> <script> import { ref } from 'vue' export default { name: 'Functions', props: { msg: String }, setup() { const codes = ref('test') codes.value = 'does it work?' return { codes } } } </script> <style> </style>
内容的提问来源于stack exchange,提问作者dataviews
相关产品推荐
相关产品推荐

