Understanding the Issue
I have created a custom system to monitor specific "store" properties from a JSON in a NoSQL database. The structure is fairly straightforward, with nested objects that are necessary for various reasons.
The data format resembles this:
{
store: {
objA: {
objB: {
prop1: 'some value'
}
}
}
}
However, when fetching the data from the NoSQL database, objB may not always be present.
Example of Template Usage
I am using custom components that rely on these data store properties:
<my-selector :value.sync="store.objA.objB.prop1">
</my-selector>
If "objB" is missing, it results in a crash with the typical JavaScript error indicating that it cannot retrieve "objB" from undefined, which is expected.
I am seeking a VueJS solution to handle this scenario.
Possible Solutions
To prevent this crash:
- Avoiding the use of v-if to hide the selector when "objB" is absent, as the selector should still be accessible even without all data being set (e.g., optional data).
- Adjusting the "load" function responsible for fetching data from the database to initialize the required properties (like objB) before assigning data to the data store. However, this approach would involve pre-defining these properties within the initial VueJS data object, a workaround I may resort to if no other feasible options emerge.
- A preferable choice involves creating a directive or another template-based solution to automatically add missing properties.
VueJS Binding Evaluation
One potential solution includes:
<my-selector v-autocreate="'store.objA.objB.prop1'" :value.sync="store.objA.objB.prop1">
</my-selector>
However, the "v-autocreate" directive binding does not take precedence initially, according to my debugging attempts. Documentation regarding the loading order of directives and attributes seems scarce.
My aim was to access all bindings of a node using the "bind" directive in order to avoid repetitive strings, similar to how we can do so in knockoutjs. Unfortunately, this functionality appears unavailable in VueJS.
While I aspire to achieve this goal, its feasibility remains uncertain. A hypothetical event like a pre-bind or beforeBind event on a directive could potentially help:
<my-selector v-autocreate :value.sync="store.objA.objB.prop1">
</my-selector>
In this case, v-autocreate would ensure the vm.$set of any missing properties.