Vue中watch监听store状态后customer.creditsLeft视图不更新求助
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

