I'm using Nuxt framework alongside Vuex to store data in my web site but I'm facing trouble when I want to use a class directly in the state.
With a model cart.js
defined like this:
export class Cart {
constructor(ownedID) {
this._created = new Date();
this._lastUpdated = new Date();
this._ownerID = ownedID || 'visitor'
this._items = []
}
getItem (articleNumber) {
console.log(this._items)
}
...
}
And my store's module cart.js
import { Cart } from "~/models/cart";
const state = () => ({
cart: new Cart()
})
const mutations = {
ADD_ITEM(state, newItem) {
console.log(state.cart)
}
}
...
When the ADD_ITEM(state, newItem)
mutation is called the getItem(articleNumber)
function is missing and thus I receive the TypeError: state.cart.getItem is not a function
error.
This is the result of the console.log
:
__ob__: Object { value: {…}, dep: {…}, vmCount: 0 }
_created:
_item:
_lastUpdated:
_ownerID:
This is a sandbox link of my setup.
Does anyone have a clue about my issue.
Thank you.
Vue accepts only plain objects & Observes only native object properties, It ignores the prototype
properties. According to the Vue documentation
The object must be plain: native objects such as browser API objects and prototype properties are ignored
In your case, your using a class
which creates variables in plain object and methods in prototype(__proto__)
, That's why state is unable to find getItem
method. You need to use plain objects
instead of classes