View profile

3 Neat Tricks With Vue Instances

In Vue, all your code is encapsulated in a Vue instance. Components are just a special type of Vue in
3 Neat Tricks With Vue Instances
By Mastering JS Weekly • Issue #17 • View online
In Vue, all your code is encapsulated in a Vue instance. Components are just a special type of Vue instance. And Vue instances have a very special property: you can instantiate them in Node.js or other JavaScript runtimes that don’t have a DOM.
Other frontend frameworks struggle with server-side rendering because your code is inherently tied to the DOM. For example, with React, you don’t get a standalone object that represents your app. You instead use the react-dom package to bootstrap your app, using completely different code than you would if you were bootstrapping your app to the DOM.
With Vue, server-side is less of a hacky afterthought and more of a first-class citizen. The design decision to have an object encapsulating your entire app has several neat consequences. Here’s 3:

1. Manually Calling Hooks
There’s some debate whether you should use Vue’s created hook or mounted hook to send HTTP requests. One common point of contention is that Vue’s server side rendering triggers the created hook, but not the mounted hook.
However, you can easily call a Vue instance’s hooks manually:
Call an async mounted hook manually for server-side rendering
Call an async mounted hook manually for server-side rendering
2. Emitting Events
You can also access a Vue instance’s child components, and even trigger events on the child components.
Once you server-side render the app, Vue creates child components
Once you server-side render the app, Vue creates child components
3. Modify Data Directly
Vue stores reactive state in the app’s `$data` property. You can go in and modify an app’s state from outside the app:
Modifying `$data` is great for testing
Modifying `$data` is great for testing
This Week's Tutorials
Did you enjoy this issue?
Mastering JS Weekly

A weekly summary of our tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue