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

Vue中watch监听store状态后customer.creditsLeft视图不更新求助

Why Your Vue Page Isn't Updating Even Though Console Shows the Correct Value

Hey there! I see you're hitting a common reactivity snag in Vue 2—let's break this down and get your page updating properly.

The Root Cause

Vue 2 has a key reactivity limitation for objects: new properties added to an object after initialization aren't automatically tracked as reactive. Your customer data starts as an empty object {}, so when you directly assign this.customer.creditsLeft = newVal, Vue doesn't recognize this new property exists. That’s why your console logs the correct value (the property does exist on the object) but the page never re-renders to show it.

Fixes You Can Implement

1. Initialize creditsLeft Upfront

Define the creditsLeft property in your customer object when you set up your data. This lets Vue track it as a reactive property from the start:

data() { 
  return {
    customer: { creditsLeft: null }, // Include creditsLeft in the initial object
  } 
},
watch: { 
  '$store.state.jobs.listBooking.customer': function (newVal) { 
    this.customer.creditsLeft = newVal; 
    console.log('current credit now' + this.customer.creditsLeft); 
  } 
},

2. Use this.$set to Add the Reactive Property

Vue provides this.$set (or Vue.set globally) to explicitly add new reactive properties to objects. This tells Vue to start monitoring the new property for changes:

data() { 
  return {
    customer: {}, 
  } 
},
watch: { 
  '$store.state.jobs.listBooking.customer': function (newVal) { 
    this.$set(this.customer, 'creditsLeft', newVal); // Replace direct assignment with $set
    console.log('current credit now' + this.customer.creditsLeft); 
  } 
},

3. Replace the Entire customer Object

Vue detects changes to object references, so you can create a new object with the updated property. This works because you’re replacing the old object with a fresh one that Vue will track:

data() { 
  return {
    customer: {}, 
  } 
},
watch: { 
  '$store.state.jobs.listBooking.customer': function (newVal) { 
    this.customer = { ...this.customer, creditsLeft: newVal }; // Spread existing properties + add creditsLeft
    console.log('current credit now' + this.customer.creditsLeft); 
  } 
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:27:42