是否可以在 Vuex/(Vue 数据)中存储自定义类的实例? [英] Is it possible to store instances of custom class in Vuex/(Vue data)?

查看:28
本文介绍了是否可以在 Vuex/(Vue 数据)中存储自定义类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 vue 文档,除了普通对象之外,不可能存储任何东西.(https://ru.vuejs.org/v2/api/#data).我一直使用vuex作为DI容器,我是从这个角度来看的.它使 vue 远离我的应用程序业务逻辑,并且可以仅使用 JS 来描述业务规则,而无需依赖.但是这种方法破坏了 vue 开发工具,并且由于某种原因并非所有测试都通过.有没有办法绕过这个限制?例如,类实例可以在 getter 中创建,而不是在 mutations 中.但这对我不起作用,因为我的类的某些构造函数有副作用(这不是最佳实践,但我拥有的).

According to vue documentation, it is not possible to store anything besides plain objects. (https://ru.vuejs.org/v2/api/#data). I always use vuex as a DI container, I see it from this point of view. It keeps vue away from my application business logic, and makes possible describe business rules only using JS with no dependencies. But that approach breaks vue dev tool, and for some reason not all tests pass. Is there a way to circumvent this restriction? For example class instances can be created in getters rather than in mutations. But it does not work for me because some constructors of my classes have side effects (It's not a best practice, but that what i have).

推荐答案

你完全可以将类实例存储在 store 状态中.

You can absolutely store class instances in the store state.

我通常存储模型数组,这对于将逻辑保持在一个地方非常有用.

I generally store arrays of models, which is really useful to keep logic in one place.

类似于:

Api.load('/api/users').then(res => commit('users', res.data.map(User.create)))

这篇关于是否可以在 Vuex/(Vue 数据)中存储自定义类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆