I am currently working on a Vue application that requires fetching data from JSP at runtime, which means I cannot use .env files. As a solution, I am attempting to set data in Vue that can be accessed throughout the entire application (components, mixins, ts modules, etc). The Vue prototype seems like a good option and it works for the Vue application, but I am facing difficulty accessing it in ts modules.
import Vue from 'vue'
import App from '@/App.vue'
class VueInstance {
data: any
constructor () {
this.data = {}
}
public setData(key: string, data: any) {
this.data[key] = data
return this
}
public init() {
Vue.prototype.$GLOBAL_DATA = this.data
new Vue({
render: (h) => h(App),
}).$mount('app')
}
}
export default function createVueInstance() {
return new VueInstance()
}
This is my JSP file where I initialize the application and pass some data:
<div id="app"></div>
<%
String javaVar = "javaVar";
%>
<aui:script require="<%= mainRequire %>">
main
.default('app')
.setData('foo', 'foo')
.setData('bar', 'bar')
.setData('javaVar', '<%= javaVar %>')
.init()
</aui:script>
Here is an example of a ts module where I need to access my global data:
const apiUrl = $GLOBAL_DATA // coming from prototype or elsewhere.
export default {
getData() {
return axios.get(`${apiUrl}/foo`)
}
}