Stringify Vue instance
Version
2.6.10
Reproduction link
https://codesandbox.io/s/vue-stringify-instance-2h78n
Steps to reproduce
Open the link, the error is reproduced right away as the code tries to serliaze the Vue instance.
What is expected?
Being able to serlialize the Vue instance.
What is actually happening?
Is not possible as the Vue prototype is missing the toJSON method.
The code is using telejson as the stringify library in order to remove circular references. Is the same utility used by Storybook 5 which will rise those errors in diferent scenarios, as for example when using the Action addon and passing as argument a Vue instance.
Yeah, there isn't a default toJSON method on classes, it's something that needs to be implemented. But I don't see what production use would toJSON have for Vue.
If the use case for this is being able to log messages during testing, error reporting or for a component style guide (like storybook), it should be implemented by those libraries so it fits their need. We cannot provide a silver bullet, dev-only toJSON
Maybe a simple Vue.prototype.toJSON = () => 'Stringifying Vue instances is not supported' in development mode would avoid confusion.
I'm labelling this as discussion because I'm not sure of the direction we should take and I don't want people to submit a PR and end up wasting their time if it gets rejected
Fair enough. Meantime a stupidly simple solution is to just do...
Vue.prototype.toJSON = function () {
return this;
};
The Vue instance can't be serialized reliably. How to “stringify” the state differs across different use cases. I prefer userland solutions like the one you posted as nobody knows what output you want better than yourself.
You can't really serialise functions (computed, methods etc), VUE relies on them to work.
If you need to serialise your vue app, you may be doing something wrong. Data can be serialised, and you can have a method for that, which can integrate with your API, but it's not easily possible to serialise a vue instance, there would be too many edge cases.
@DominusVilicus, seriliazing an Object is quite common, a Vue instance is not more than that and all the edge cases are dealed by the serializing library. As stated in my last answer the solution is to just add the missing _toJSON function which could return the entire Vue instance or a new Object with just the important parts, as the $data.
This can be implemented in userland, I'm sure there's uses for this, but most users won't need to use this.
This would be better implemented as a plugin or library
That's fine with me.