Vue类组件属性在HTML模板中不响应的问题排查
问题原因及解决方案
你遇到的UI不更新问题,核心原因是缺少@Component装饰器。vue-class-component依赖这个装饰器将类转化为Vue组件实例,只有这样类中的属性才会被Vue的响应式系统追踪,修改属性时才能触发UI同步更新。
修复步骤
- 首先导入
Component装饰器:
import { Component, mixins } from 'vue-class-component';
- 为组件类添加
@Component装饰器:
@Component export default class Withdraw extends mixins(Global, Authenticated) { walletAssets = JSON.parse(this.$store.getters.userWalletAssets); coinBallance = this.walletAssets[0].bal; coinType = this.walletAssets[0].symbol; coinsAmount: number; walletAddress: string; transactionFee = 0.0; UpdateUserCryptoBal(ballance: any, coinType: any) { this.coinBallance = ballance; this.coinType = coinType; console.log(this.coinType, this.coinBallance); } }
额外优化建议
1. 让walletAssets响应store变化
当前walletAssets是初始化时直接赋值,不会同步store中userWalletAssets的后续更新,建议改成计算属性:
@Component export default class Withdraw extends mixins(Global, Authenticated) { coinsAmount: number; walletAddress: string; transactionFee = 0.0; coinBallance = 0; coinType = ''; // 用计算属性监听store数据变化 get walletAssets() { return JSON.parse(this.$store.getters.userWalletAssets) || []; } mounted() { // 初始化默认资产数据 this.initDefaultBal(); } initDefaultBal() { if (this.walletAssets[0]) { this.coinBallance = this.walletAssets[0].bal; this.coinType = this.walletAssets[0].symbol; } } UpdateUserCryptoBal(ballance: any, coinType: any) { this.coinBallance = ballance; this.coinType = coinType; console.log(this.coinType, this.coinBallance); } }
2. 避免空值报错
在访问walletAssets[0]时添加可选链判断,防止store数据为空时出现报错。
内容的提问来源于stack exchange,提问作者MAXWEL OCHIENG
相关产品推荐
相关产品推荐

