11 |
12 |
13 | # Quench Vue
14 |
15 | **Simple, tiny, client-side hydration of pre-rendered [Vue.js](https://vuejs.org) apps**
16 |
17 | Quench Vue allows server-rendered/static markup to be used as a Vue app's `data`, `template` and local components' `template`s. It's great for when you can't/don't want to use "real" [server-side rendering](https://vuejs.org/v2/guide/ssr.html).
18 |
19 | All of Vue's existing features will work as normal when the app is initialised in the browser.
20 |
21 | ## Table of Contents
22 |
23 | - [Demo](#demo)
24 | - [Installation](#installation)
25 | - [npm](#npm)
26 | - [Direct `
75 | ```
76 |
77 | *Note: You will need to use [the full build of Vue.js](https://vuejs.org/v2/guide/installation.html#Explanation-of-Different-Builds), which includes the compiler.*
78 |
79 | ## Usage
80 |
81 | 1. [Defining the app `data` and `template`](#defining-the-app-data-and-template).
82 | 2. [Defining local component `template`s](#defining-local-component-templates).
83 |
84 | ## Defining the app `data` and `template`
85 |
86 | There are 2 ways of defining and using `data` for the app:
87 |
88 | 1. With a stringified JSON object in the app container's `q-data` attribute; and/or
89 | 2. With an inline `q-binding` attribute on an element, when `q-convert-bindings` is added to the app container.
90 |
91 | Both techniques can be used together or on their own, but the `q-data` is preferred as it's faster, simpler and more versatile.
92 |
93 | Let's look at some examples:
94 |
95 | ### Method 1: Defining the `data` with `[q-data]`
96 |
97 | This method allows you to easily specify the `data` for the app, including arrays and objects.
98 |
99 | ```html
100 |
122 | …
123 |
124 | ```
125 |
126 | #### Rendering the data with `[v-text]`
127 |
128 | We obviously duplicate the "data" in the markup, and inform Vue which elements are bound to which `data` properties using a [`v-text`](https://vuejs.org/v2/api/#v-text) attribute whose value points to a property name, such as:
129 |
130 | ```html
131 |
Hello, World!
132 |
2018
133 |
134 |
135 |
136 | js
137 |
138 |
139 |
140 | library
141 |
142 |
143 |
144 |
145 |
146 |
147 | Matt
148 |
149 |
150 |
151 | Stow
152 |
153 |
154 |
155 |
156 |
157 |
158 | JS
159 | 4
160 |
161 |
162 |
163 | CSS
164 | 5
165 |
166 |
167 |
168 | ```
169 |
170 | For iterating over lists, we also need to use another syntax, ` … `, which [we'll describe later](#hiding-elements-from-the-compiler).
171 |
172 | *Note:*
173 | * *You can also use [`v-html`](https://vuejs.org/v2/api/#v-html) to render HTML, but ensure that it's sanitized and trusted.*
174 | * *You only need to output the `v-for` and the `v-text`/`q-binding` attributes on the first iteration of the loop.*
175 |
176 | ### Method 2: Defining the `data` with inline `[q-binding]` bindings
177 |
178 | While we don't recommend the following approach for anything but the simplest of apps, when `q-convert-bindings` is set on the app's container, we can also use the `q-binding` attribute to create a `data` variable that is equal to the value of the element's `.textContent`.
179 |
180 | *Note:*
181 | * *Bindings specified in the global `q-data` object take precedence over inline bindings.*
182 | * *Do not nest elements inside a `q-binding` element, or you'll have unexpected results.*
183 |
184 | The following examples all perfectly re-create the global `q-data` object from before.
185 |
186 | #### Simple bindings
187 |
188 | ```html
189 |
190 |
Hello, World!
191 |
2018
192 |
193 | ```
194 |
195 | #### Array and Object bindings
196 |
197 | Vue supports iterating over arrays and objects via [the `v-for` directive](https://vuejs.org/v2/guide/list.html) with the syntax `item in items`, where `items` is the source data list and `item` is an **alias** for the array element being iterated on.
198 |
199 | To inline bind with Quench, we need to use another special syntax `itemsSource as item`.
200 |
201 | ##### Array
202 |
203 | To replicate the `tags` array from above, we would:
204 |
205 | ```html
206 |
207 |
208 |
209 | js
210 |
211 |
212 |
213 | library
214 |
215 |
216 |
217 |
218 | ```
219 |
220 | where `itemsSource` is the name of the array (`tags`) plus the index in the array `[0]`/`[1]` which we wish to populate, and `tag` is the `item` alias in the `v-for`.
221 |
222 | ##### Object
223 |
224 | To replicate the `author` object from above, we would:
225 |
226 | ```html
227 |
228 |
229 |
230 | Matt
231 |
232 |
233 |
234 | Stow
235 |
236 |
237 |
238 |
239 | ```
240 |
241 | where `itemsSource` is the name of the object (`author`) plus the relevant object key `.firstName`/`.lastName` which we wish to populate, and `key` is the `item` alias in the `v-for`.
242 |
243 | ##### Array of Objects
244 |
245 | Both of the above techniques can be combined, so to replicate the `skills` array from above, we would:
246 |
247 | ```html
248 |
249 |
250 |
251 | JS
252 | 4
253 |
254 |
255 |
256 | CSS
257 | 5
258 |
259 |
260 |
261 |
262 | ```
263 |
264 | where `itemsSource` is the name of the array and index (`skills[0]`) plus the relevant object key `.name`/`.level` which we wish to populate, and `skill.name`/`skill.level` is the `item` alias in the `v-for` plus the object key.
265 |
266 | Hopefully you'll agree that using inline bindings to set the `data` is more complicated than using the `q-data` method, but it can still have its uses.
267 |
268 | *Note: When using inline bindings, arrays and objects are limited to a depth of 1 level.*
269 |
270 | #### Non-element bindings
271 |
272 | Since v0.7.0, you can also create `data` from bindings using specially formatted comments, thus not requiring to have actual elements to attach to. This can be useful if you need to create extra `data` that is "invisible" to the user, or if you need to create more complex values, such as nested arrays and objects.
273 |
274 | Using the syntax `` we can easily recreate the `data` from the previous examples:
275 |
276 | ```html
277 |
289 | ```
290 |
291 | However, we can also create more complex `data` values. The following recreates the above arrays and objects succinctly.
292 |
293 | ```html
294 |
295 |
296 |
297 |
298 |
299 | ```
300 |
301 | *Note: Non-element bindings must be JSON-serializable and written on one line.*
302 |
303 | ### Referencing global variables as `data` properties
304 |
305 | You can also pass global variables (on `window`) to be used as data properties. Similarly to `q-data`, we can pass a stringified JSON object of key/value pairs to a `q-r-data` attribute, where *key* is the name of the `data`'s property and *value* the name of the global variable to be used, which can also use dot notation to access properties of an object.
306 |
307 | ```html
308 |
316 |
322 | ```
323 |
324 | which will produce the following `data`:
325 |
326 | ```js
327 | {
328 | env: 'dev',
329 | port: 3000,
330 | foo: 'bar',
331 | baz: 'qux',
332 | }
333 | ```
334 |
335 | *Note: Bindings specified in the `q-r-data` object take precedence over those in `q-data`.*
336 |
337 | ### Excluding elements from the app template compiler
338 |
339 | In the previous sections, we introduced the ` … ` syntax. These are a pair of opening and closing comments that exclude the contents within from being passed to the template compiler.
340 |
341 | The most obvious use case (and necessary when using inline bindings) is to strip all but the first element of a `v-for` loop as demonstrated earlier.
342 |
343 | Another use case is to replace static markup for a component, such as:
344 |
345 | ```html
346 |
347 |
I will be stripped in the app and "replaced" with the component version below
348 |
349 |
350 | ```
351 |
352 | *Note: Nesting comments is not supported.*
353 |
354 | ### Instantiating the app
355 |
356 | Very little needs to change from the way you'd normally instantiate an app.
357 |
358 | #### With a module bundler, such as webpack
359 |
360 | ```js
361 | import Vue from 'vue';
362 | import { createAppData, createAppTemplate } from 'quench-vue';
363 |
364 | var appEl = document.getElementById('app');
365 | var data = createAppData(appEl);
366 | var template = createAppTemplate(appEl);
367 |
368 | var app = new Vue({
369 | el: appEl,
370 | data: data,
371 | template: template,
372 | });
373 | ```
374 |
375 | #### For direct `
379 |
380 | ```
381 |
382 | ```js
383 | var appEl = document.getElementById('app');
384 | var data = quenchVue.createAppData(appEl);
385 | var template = quenchVue.createAppTemplate(appEl);
386 |
387 | var app = new Vue({
388 | el: appEl,
389 | data: data,
390 | template: template,
391 | });
392 | ```
393 |
394 | ## Defining local component `template`s
395 |
396 | Vue applications are often comprised of multiple components, which promotes reuse and reduces repetition. However, the more components you have, the greater your JavaScript bundle will be. While complex components, such as interactive UI widgets should probably be defined in JavaScript, simpler, more display-only components can easily be defined from existing, pre-rendered HTML with Quench Vue.
397 |
398 | Defining local component `template`s from existing markup suits situations such as an infinite scroll of news cards, where the original "page" of cards are pre-rendered, and as a user scrolls, your Vue app needs to fetch and append more cards from a JSON API response.
399 |
400 | *Note: You cannot use Quench Vue to specify the `template` of global components created with `Vue.component()`. We consider global components an anti-pattern anyway.*
401 |
402 | ### Specifying a component with `[q-component]`
403 |
404 | Any element within your app's `el` can be used as the markup for a component by adding an attribute of `q-component="NAME"`, where `"NAME"` is the name of the local component defined in your Vue app.
405 |
406 | Typically, this would be on a `
` or similar, which sets the `outerHTML` of the element to be used as the `template`. However, you can also use a `` element as the component definition, in which case the `innerHTML` becomes the `template`.
407 |
408 | For instance:
409 |
410 | ```html
411 |
412 |
440 | ```
441 |
442 | *Note:*
443 | * *Only the first instance of `q-component="NAME"` will be used as the component's `template`.*
444 | * *Components need to be wrapped in ` … ` comments to prevent them from being included in the app's template.*
445 | * *We opted for a custom, `q-component` syntax (compared with Vue's native [`inline-template`](https://vuejs.org/v2/guide/components.html#Inline-Templates) syntax) for various reasons, but mainly because it allows for greater flexibility in the types of templates that can be defined (such as `
`s with multiple children), and we can supplement with additional features as described below.*
446 |
447 | ### Specifying a component's `template`
448 |
449 | The previous templates aren't particularly useful, but as you'd expect, any Vue directives or template syntax can be used and will be converted, similar to the app's template above (with the exception of not supporting Quench Vue's `q-binding`).
450 |
451 | Take the following HTML:
452 |
453 | ```html
454 |
503 | ```
504 |
505 | ### Handling a `template`'s logic
506 |
507 | While the previous template will handle content and style differences, it's not uncommon for a component's markup to also change based on certain conditions. There a 3 ways in which we can handle these logic requirements:
508 |
509 | 1. Add the logic within the markup (often using `` so they're invisible in the pre-rendered markup).
510 | 2. Add the logic within the component's JavaScript using a proprietary `partials` object and reference it with a special `` syntax; or
511 | 3. Define a completely different component.
512 |
513 | Let's look at some examples:
514 |
515 | #### Method 1: Add the logic within the markup
516 |
517 | ```html
518 |
547 | ```
548 |
549 | This will most likely be the primary method used to handle template logic, however, with complex conditions, you may like to consider the following 2 approaches.
550 |
551 | #### Method 2: Add the logic to the component's JavaScript using `partials`
552 |
553 | When defining the component in JavaScript, add a `partials` object with a name and template string key/value pair, like so:
554 |
555 | ```js
556 | components: {
557 | card: {
558 | partials: {
559 | image: `
560 |
561 |
565 |
566 |
567 |
568 |
569 | ` // Using ES6 template literals, but any string concatenation method works
570 | },
571 | template: 'local'
572 | }
573 | }
574 | ```
575 |
576 | and reference it in the pre-rendered component with ``:
577 |
578 | ```html
579 |
600 | ```
601 |
602 | When the template is compiled, this `` will be converted to the value of the app's `components.partials.image` property.
603 |
604 | This method allows you to move more complex or repetitive logic into the JavaScript to reduce the size of the pre-rendered HTML.
605 |
606 | *Note: Having a `` element within your markup could affect your layout. There are 2 solutions to this problem:*
607 | 1. *Add `q-component-partial { display: none; }` to your CSS; or*
608 | 2. *Wrap HTML comments around the tag ``, which reduces the need for extra CSS, but may make the HTML less obvious in your editor.*
609 |
610 | #### Define a completely different component
611 |
612 | Instead of handling the logic in the front-end, you could define separate component variations in the pre-rendered HTML. The downside to this approach is, that if your original markup didn't contain a component variation which was later used, Vue would throw an error. A workaround to this is to output a `` as a fallback for all possible variations that weren't in the original data.
613 |
614 | Here we define 2 components, `card--default` and `card--fallback`, and remove all the `v-if` logic from the markup.
615 |
616 | ```html
617 |
659 |
660 | ```
661 |
662 | ### Excluding elements from the component template compiler
663 |
664 | Similarly to [excluding elements from the app template compiler](#excluding-elements-from-the-app-template-compiler), elements within a component can be excluded from its template by being wrapped in a pair of ` … ` comments as demonstrated in the earlier examples.
665 |
666 | ### Rendering future components dynamically
667 |
668 | While components are normally rendered with their name in angled brackets (``), Vue also [supports a meta component (``)](https://vuejs.org/v2/api/#component) which allows us to programmatically render a component of our choice.
669 |
670 | Assuming we had 4 card variations: `card--default`, `card--fallback`, `card--twitter` and `card--instagram`, we can use a unique variable (often a property on the card's `props` object such as `type`) to selectively render future components of that type using the `is` attribute.
671 |
672 | Here we iterate over our `cards` array, dynamically render the correct card component based on `card.type` and pass the card's data to the `props` prop.
673 |
674 | ```html
675 |
676 |
680 |
681 | ```
682 |
683 | ```js
684 | [
685 | {
686 | type: 'card--twitter',
687 | title: 'Arguing on the Internet still rampant',
688 | …
689 | },
690 | {
691 | type: 'card--default',
692 | title: 'Mario Bros And Other Nintendo Arcade Games Coming To Nintendo Switch',
693 | …
694 | },
695 | {
696 | type: 'card--instagram',
697 | title: 'Check out this selfie of me and my avocado',
698 | …
699 | },
700 | {
701 | type: 'card--fallback',
702 | title: 'Doom 2016 Is Coming To Nintendo Switch',
703 | …
704 | }
705 | ]
706 | ```
707 |
708 | ### Updating our app initialization to support pre-rendered components
709 |
710 | Very little needs to change [from our earlier example](#instantiating-the-app).
711 |
712 | #### With a module bundler, such as webpack
713 |
714 | ```js
715 | import Vue from 'vue';
716 | import { createAppData, createAppTemplate, createComponentTemplates } from 'quench-vue'; // import createComponentTemplates
717 |
718 | var appEl = document.getElementById('app');
719 | var data = createAppData(appEl);
720 | var components = {
721 | 'card--default': { // Register all possible components for this app
722 | props: ['props'], // Define props as you normally would
723 | template: 'local', // Specify that the component's template is "local"
724 | },
725 | 'card--fallback': {
726 | props: ['props'],
727 | template: 'local',
728 | },
729 | 'card--instagram': {
730 | props: ['props'],
731 | template: 'local',
732 | },
733 | 'card--twitter': {
734 | props: ['props'],
735 | template: 'local',
736 | }
737 | };
738 | components = createComponentTemplates(appEl, components); // Convert and add templates to your components
739 | var template = createAppTemplate(appEl); // createAppTemplate has to be called after createComponentTemplates
740 |
741 | var app = new Vue({
742 | el: appEl,
743 | components: components,
744 | data: data,
745 | template: template,
746 | });
747 | ```
748 |
749 | *Note: camelCase component names are converted to kebab-case, so you can use [object shorthand notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions) to define your components after `import`ing them*
750 |
751 | #### For direct `
755 |
756 | ```
757 |
758 | ```js
759 | var appEl = document.getElementById('app');
760 | var data = quenchVue.createAppData(appEl);
761 | var components = {
762 | 'card--default': { // Register all possible components for this app
763 | props: ['props'], // Define props as you normally would
764 | template: 'local', // Specify that the component's template is "local"
765 | },
766 | 'card--fallback': {
767 | props: ['props'],
768 | template: 'local',
769 | },
770 | 'card--instagram': {
771 | props: ['props'],
772 | template: 'local',
773 | },
774 | 'card--twitter': {
775 | props: ['props'],
776 | template: 'local',
777 | }
778 | };
779 | components = quenchVue.createComponentTemplates(appEl, components); // Convert and add templates to your components
780 | var template = quenchVue.createAppTemplate(appEl); // createAppTemplate has to be called after createComponentTemplates
781 |
782 | var app = new Vue({
783 | el: appEl,
784 | components: components,
785 | data: data,
786 | template: template,
787 | });
788 | ```
789 |
790 | ## Hiding elements in the pre-rendered HTML
791 |
792 | To prevent layout jumping and repositioning when the app's template gets compiled, it can be beneficial to visually (and accessibly) hide elements and content that is inappropriate without JavaScript, such as a `