I have a Vue CLI app that I want to connect to a server back-end.
The server will return a view template with a data payload, and I want to inject that payload as JSON into the Vue app as a data property.
The index.html
file generated by Vue CLI looks like the following (I set filenameHashing
to false
in vue.config.js
to avoid random file names):
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<meta http-equiv=X-UA-Compatible content="IE=edge">
<meta name=viewport content="width=device-width,initial-scale=1">
<link href=/css/app.css rel=preload as=style>
<link href=/css/chunk-vendors.css rel=preload as=style>
<link href=/js/app.js rel=preload as=script>
<link href=/js/chunk-vendors.js rel=preload as=script>
<link href=/css/chunk-vendors.css rel=stylesheet>
<link href=/css/app.css rel=stylesheet>
</head>
<body>
<div id=app>
</div>
<script src=/js/chunk-vendors.js></script>
<script src=/js/app.js></script>
</body>
</html>
And main.js
looks like the following:
import Vue from 'vue';
import SiteContainer from './components/layout/SiteContainer.vue';
new Vue({
render: h => h(SiteContainer)
}).$mount('#app');
I want to be able to do something like the following:
<div id="app" :data="{{ json-string-of-data-payload-from-server }}">
So that I can then access the data in SiteContainer
as follows:
props: [
'data'
]
I've tried essentially doing what I wrote above, but because the render
method seems to completely replace the #app
div with the site-container
component, the :data
property is lost as well.
I also saw that you can pass a second argument to render
with data, but I couldn't figure out how to make it work, and ultimately, that's in main.js
, not the view template file that the server will use, which is where I need the JSON data to be to get it from the server to the Vue app.
How can I pass data from the server-generated view template to the Vue CLI app to get everything going? Thank you.
I was able to figure it out.
By defining the
SiteContainer
component as a Vue.js component inmain.js
first, I am able to freely use the component in the HTML file to get what I want.Specifically, I changed the
main.js
file as follows:And then the
body
part of the HTML file becomes the following (i.e., replace the#app
div
that I had in my question above):