I am having some troubles trying to use “this” in a deep watcher. It seems like inside the deep watcher, the word this points to the context of the object watcher and it is not able to get an attribute declared in the data() function. My script tag looks like this:
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "App",
data() {
return {
totalPrice: 0,
cart: new Array<any>()
};
},
watcher: {
cart: {
handler(cart: Array<any>) {
this.totalPrice = cart.reduce((prev, curr) => {
const prevPrice = prev.price || prev;
const prevQuantity = prev.quantity || 1;
return prevPrice * prevQuantity + curr.price * curr.quantity;
}, 0);
},
deep: true
},
},
});
</script>
So, when I do npm run serve
I get this error in console:
ERROR in src/App.vue:134:14
TS2339: Property 'totalPrice' does not exist on type '{ handler(cart: any[]): void; deep: boolean; }'.
133 | handler(cart: Array<any>) {
> 134 | this.totalPrice = cart.reduce((prev, curr) => {
| ^^^^^^^^^^
135 | const prevPrice = prev.price || prev;
136 | const prevQuantity = prev.quantity || 1;
137 | return prevPrice * prevQuantity + curr.price * curr.quantity;
I’m new with vue, so I’ll be happy receiving any suggestion. Thanks in advance.