It's crucial to consider timing when working with Vue and window.appSettings. To ensure proper execution, it is recommended to write to window.appSettings within a created or mounted function.
For instance:
{
mounted() {
window.appSettings = window.appSettings || {};
window.appSettings.userId = this.userId;
}
}
Since these values will be used by an external script, Vue must set them BEFORE the script loads. One way to achieve this is by having Vue handle the loading of the external script itself. This can be done by dynamically creating a script element and adding it to the dom:
{
mounted() {
// write the values first
window.appSettings = window.appSettings || {};
window.appSettings.userId = this.userId;
// now load any external scripts:
var script = document.createElement('script');
script.src = 'hellozest.io/widget/...';
document.body.appendChild(script);
}
}
While this approach may work, it does require Vue to have knowledge of and responsibility for external scripts. In general, it might be preferable to address this issue differently:
If userId and userEmail are accessible on the backend of your application, consider setting 'window.appSettings' on the server side to keep the Vue application simple. Alternatively, if only Vue has access to these values, you could isolate this functionality within a single Vue component to maintain code structure.