2

I'm still learning Vue.js 2 so I do apologize if this question is a bit silly. I'm building an application using MongoDB, Node, Express and Vue. Normally I'd use a template engine such as Ejs where data passed through Express's res.render method can be readily captured in the template.

Is there a similar way to pass data from backend to the root Vue component? For example, normally, a get request fetches some data from Mongodb, express will render the template file and pass data to it.

app.get("/gallery/:id", function(res, req) {

var id = req.params.id;

database.findById(id, function(err, data) {
....
res.render("home", data);

}
}); 

Now my root Vue application is attached to html file. I'd like to be able to dynamically render the app with data returned from the database.

I've built an app before that streams data from an api and passed it to my Vue component via socket but I feel like using a socket in this case is unnecessary.

2 Answers 2

1

Use http. What's the problem? You can use XmlHttp, or a lot of folk seem to be using Axios. Trigger the call in the onload of your page, or use one of the vue lifecycle hooks. The very good vue docs don't have much to say about how and when to do this. We do it in the onload of the page, and we instantiate vue when the request for page data returns.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, I just figured it out. I was just following the documentation and building things as I go, didn't know there was a vue-resource package. Thank you for you help :)
Vue-resource has been moved to the back burner. I have no opinion. We're still using a thin promise wrapper over xmlhttp that I wrote. Need to get modern.
1

The question has already been answered, but I wanted to share my approach. I've been experimenting with rendering an object server side using res.render(), putting it in a div where display: none, and then grabbing the object on the client and passing it to Vue's data attribute.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.