A
A
andrei_pro2019-07-02 09:42:33
Vue.js
andrei_pro, 2019-07-02 09:42:33

Are such vuex mutations correct?

Hello.
There is a class:

export default class Product {
    constructor(name) {
        this.name = name
        this.comments = []
    }

    addComment(comment) {
        this.comments.push(comment)
    }

    removeComment(comment) {
        const idx = this.comments.indexOf(comment)

        if (idx !== -1) {
            this.comments.splice(idx, 1)
        }
    }
}

export default class Comment {
    constructor(name) {
        this.name = name
    }
}

There is storage:
const store = new Vuex.Store({
  state: {
    products: []
  },
  mutations: {
    addCommentToProduct(state, {product, comment}) {
        product.addComment(comment)
    },
   actions: {
      addCommentToProduct() {
         const product = new Product('product 1')
         const comment = new Comment('comment 1')
 
         const data = {product, comment}
         commit('addCommentToProduct', data)
      }
   }
  }
});

1. Is it possible to make changes like this in a mutation? (call class functions, not write code in mutation)
2. When I work with classes and call their functions, example product.addComment(), then after saving the entire state to the server, the api returns me a regular json, which is in no way connected with classes and from this all functions do not work. Do I need to do products.map(product => new Product(product)) and all nested objects to create classes from an array? It is not possible to use orm

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nvdfxx, 2019-07-02
@nvdfxx

It looks very strange, there are products in the state, but there is no work with it in actions / mutations, or am I missing something? How do you get changes into the state after, for example, addCommentToProduct?

E
Evgeny Kulakov, 2019-07-02
@kulakoff

In my opinion, this will create difficulties, especially in terms of the reactivity of the store, which will outweigh the benefits of using a class for the model. Vuex works well with flat objects and simple data types. In your version, in order for everything to work without dancing with a tambourine and catching bugs related to the fact that reactivity has fallen off somewhere, you need to recreate the entity every time you change it and merge the previous state with the new one, which will be that hemorrhoids IMHO. Plus, such a re-creation affects performance in general, because. getters/setters will be created for object fields each time to ensure reactivity. If there are a lot of objects, this starts to affect. In general, vue is mutable in nature, this is its advantage and disadvantage at the same time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question