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

Vue3为何无法正确显示Getter属性值?

Vue3 无法正确显示 Class Getter 属性值的问题

我有一个如下的 Class 模型:

export class Coordinate {
  file: string;
  row:  number;
  public get toString(): string{
    return `${this.file}${this.row}`;
  }
  constructor(file: string, row:  number){
    this.file = file;
    this.row = row;
  }
}

将该对象通过自定义组件的 props 传递后,遇到以下显示问题:

  • 直接访问 toString 显示内容为 function toString() { [native code] }:
    <p>👎 {{ myObject.coordinate.toString }} 👎</p>
    
  • 调用 toString() 显示内容为 [object Object]:
    <p>👎 {{ myObject.coordinate.toString() }} 👎</p>
    
  • 改为箭头函数属性后,调用 myOject.coordinate.asString 返回 undefined,调用 .asString() 时控制台报错(TypeScript 无提示):
    asString = () => `${this.file}${this.file}`;
    
  • 直接拼接属性可正常显示,但并非理想方案:
    <p>👍 {{ myObject.coordinate.file }}{{ myObject.coordinate.row }} 👍</p>
    

解决方案

1. 重命名 Getter 避免覆盖原生方法

所有对象都继承了 Object.prototype.toString 原生方法,你定义的 toString Getter 没有正确覆盖它,导致 Vue 访问时优先拿到原生方法。只需给 Getter 改名即可:

export class Coordinate {
  file: string;
  row: number;
  // 自定义 Getter 名称
  public get coordString(): string {
    return `${this.file}${this.row}`;
  }
  constructor(file: string, row: number) {
    this.file = file;
    this.row = row;
  }
}

模板中直接访问该 Getter:

<p>👍 {{ myObject.coordinate.coordString }} 👍</p>

2. 正确覆盖原生 toString 方法

如果一定要保留 toString 名称,不要用 Getter,直接定义同名方法覆盖原生实现:

export class Coordinate {
  file: string;
  row: number;
  constructor(file: string, row: number) {
    this.file = file;
    this.row = row;
  }
  // 覆盖原生 toString 方法
  toString(): string {
    return `${this.file}${this.row}`;
  }
}

模板中调用方法即可正常显示:

<p>👍 {{ myObject.coordinate.toString() }} 👍</p>

3. 修复箭头函数属性的响应式问题(针对第三种尝试)

箭头函数作为 Class 属性时,对象被 Vue 转为 Proxy 后可能丢失绑定。若要使用这种方式,需在传递实例前用 markRaw 标记为不被代理:

import { markRaw } from 'vue';

// 创建实例时包裹 markRaw
const coordinate = markRaw(new Coordinate('b', 2));
// 再将该实例传入组件 props

模板中调用箭头函数:

<p>👍 {{ myObject.coordinate.asString() }} 👍</p>

注:此方法复杂度较高,优先推荐前两种方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 11:48:19