You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中computed属性无法显示值:问题排查与修复咨询

问题原因分析
  • 箭头函数导致this指向异常:Vue的computed属性中使用箭头函数时,箭头函数不会绑定自身的this,而是继承外层作用域的this,这个this并非Vue组件实例,因此无法访问到实例上的name_属性,最终触发'name_' is not defined报错。
  • 额外注意:代码中components里注册的HelloWorld未导入,虽不是当前报错的直接原因,但会导致该组件无法正常使用,若需使用请补充导入语句。
修复方案
  1. 将computed中的箭头函数替换为普通函数,让this正确指向Vue组件实例;
  2. (可选)若需使用HelloWorld组件,补充对应的导入语句。

修复后的完整代码:

<template>
  <div>computedProps:{{ calculated }}</div>
</template>

<script>
// 若使用HelloWorld组件,需按实际文件路径导入,示例如下
// import HelloWorld from './components/HelloWorld.vue'

export default {
  name: "App",
  components: {
    HelloWorld
  },
  data() {
    const name_ = "ertz"
    const address_ = "aasf"
    const phone_ = "100 xx 50"
    return{
      name_,
      address_,
      phone_
    }
  },
  computed: {
    // 替换为普通函数
    calculated(){
      return this.name_.length
    }
  }
};
</script>

内容的提问来源于stack exchange,提问作者Amrmsmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:52:02