Router Component

Router Component is a special type of content that can be loaded by Router when we specify route content using component or componentUrl properties.

It should help to better structure our apps, keep things in appropriate place, and make many things quicker and in a more clear and comfortable way.

Component Structure

If you know what is Vue component, then it will be much easier to understand as it looks pretty similar. Router Component is basically an object with the following properties (all properties are optional):

PropertyTypeDescription
templatestringTemplate7 template string. Will be compiled as Template7 template
renderfunctionRender function to render component. Must return full html string or HTMLElement
datafunctionComponent data, function must return component context data
stylestringComponent CSS styles. Styles will be added to the document after component will be mounted (added to DOM), and removed after component will be destroyed (removed from the DOM)
methodsobjectObject with additional component methods which extend component context
onobjectObject with page events handlers
Lifecycle Hooks
beforeCreatefunctionCalled synchronously immediately after the component has been initialized, before data and event/watcher setup.
createdfunctionCalled synchronously after the component is created, context data and methods are available and component element $el is also created and available
beforeMountfunctionCalled right before component will be added to DOM
mountedfunctionCalled right after component was be added to DOM
updatedfunctionCalled right after component VDOM has been patched
beforeDestroyfunctionCalled right before component will be destoyed
destroyedfunctionCalled when component destroyed

All lifecycle hooks and methods automatically have their this context bound to the component context, so that you can access component data and methods. This means you should not use an arrow function to define a lifecycle method (e.g. created: () => this.doSomething()). The reason is arrow functions bind the parent context, so this will not be the component instance as you expect and this.doSomething will be undefined.

So the example route with page component may look like:

  1. routes = [
  2. // ...
  3. {
  4. path: '/some-page/',
  5. // Component Object
  6. component: {
  7. template: `
  8. <div class="page">
  9. <div class="navbar">
  10. <div class="navbar-inner">
  11. <div class="title">{{title}}</div>
  12. </div>
  13. </div>
  14. <div class="page-content">
  15. <a @click="openAlert" class="red-link">Open Alert</a>
  16. <div class="list simple-list">
  17. <ul>
  18. {{#each names}}
  19. <li>{{this}}</li>
  20. {{/each}}
  21. </ul>
  22. </div>
  23. </div>
  24. </div>
  25. `,
  26. style: `
  27. .red-link {
  28. color: red;
  29. }
  30. `,
  31. data: function () {
  32. return {
  33. title: 'Component Page',
  34. names: ['John', 'Vladimir', 'Timo'],
  35. }
  36. },
  37. methods: {
  38. openAlert: function () {
  39. var self = this;
  40. self.$app.dialog.alert('Hello world!');
  41. },
  42. },
  43. on: {
  44. pageInit: function (e, page) {
  45. // do something on page init
  46. },
  47. pageAfterOut: function (e, page) {
  48. // page has left the view
  49. },
  50. }
  51. },
  52. },
  53. // ...
  54. ]

Component Context

As we said above, all component methods and Template7 compiler are executed in the context of the component.

Component context is the object you have returned in component’s data and methods from specified methods object, but also extended with the following useful properties:

PropertyTypeDesctiption
$elobject

Dom7 instance with component HTML element

  1. this.$el.find(‘p’).addClass(‘red’)
$
$$
$dom7
function

Dom7 library:

  1. this.$$(‘p’).text(‘hello world’)
$app
$f7
object

Framework7 app instance

  1. this.$app.dialog.alert(‘Hello world!’)
  2. / or /
  3. this.$f7.dialog.alert(‘Hello world!’)
$rootobject

Root data and methods you have specified in data and methods properties on app init

  1. var app = new Framework7({
  2. // root data
  3. data: function () {
  4. return {
  5. username: johndoe
  6. }
  7. },
  8. // root methods
  9. methods: {
  10. helloWorld: function () {
  11. app.dialog.alert(‘Hello world!’);
  12. }
  13. }
  14. });
  15. // then in component:
  16. console.log(this.$root.username); // -> ‘johndoe’;
  17. this.$root.helloWorld(); // -> call alert
$route
$f7route
objectCurrent route. Contains object with route query, hash, params, path and url
$router
$f7router
Router instance

Related router instance

  1. this.$router.back(); //navigate back
$idstring

Component id, used as scoped styles id

$themeobject

Object with md, ios and aurora boolean properties which indicating current theme. For example:

  1. if (this.$theme.ios) { / do something when iOS theme is active / }
  2. if (this.$theme.md) { / do something when MD theme is active / }
  3. if (this.$theme.aurora) { / do something when Aurora theme is active / }
$setState()function

Component method where you pass mergeState object that will be merged with current component state. It is the method that tells to component that its state has been changed and it must be rerendered. It launches the process of VDOM comparison and patching of necessary elements and attributes in real DOM.

Such mechanism is similar to React’s approach and its method. It allows to control rendering and avoid unnecessary renders.

Note, that direct assignment to component state won’t trigger layout update. If we use this.foo = ‘bar’ it will not be updated. Use $setState() whenever you need to update component layout!

Component Page Events

Component page events handlers can be passed in on component property. They are usual DOM Page Events. Because they are DOM events, they accept event as first agrument, and Page Data as second argument. There only difference with usual DOM events is that their context (this) bound to component context and event handler name must be specified in camelCase format (page:init -> pageInit):

  1. ...
  2. data: function () {
  3. return {
  4. username: 'johndoe',
  5. };
  6. },
  7. on: {
  8. pageMounted: function (e, page) {
  9. console.log('page mounted');
  10. },
  11. pageInit: function (e, page) {
  12. console.log(this.username); // -> 'johndoe'
  13. },
  14. pageBeforeIn: function (e, page) {
  15. console.log('page before in');
  16. },
  17. pageAfterIn: function (e, page) {
  18. console.log('page after in');
  19. },
  20. pageBeforeOut: function (e, page) {
  21. console.log('page before out');
  22. },
  23. pageAfterOut: function (e, page) {
  24. console.log('page after out');
  25. },
  26. pageBeforeUnmount: function (e, page) {
  27. console.log('page before unmount');
  28. },
  29. pageBeforeRemove: function (e, page) {
  30. console.log('page before remove');
  31. },
  32. }

DOM Events Handling

Note that additional @ attribute in component template. It is a shorthand method to assign event listener to the specified element. Specified event handler will be searched in component methods.

Such event handlers are processed only on initial rendering, or for elements patched with VDOM. If you add such element to DOM manually it won’t work!

  1. {
  2. // ...
  3. methods: {
  4. onClick: function() {
  5. // ...
  6. }
  7. },
  8. on: {
  9. pageInit: function (page) {
  10. // this won't work
  11. page.$el.append('<a @click="onClick">Link</a>');
  12. }
  13. }
  14. }

Component Root Element

Component template or render function must return only single HTML element. And it must be an element that is supported by router:

  • If you load pages as router component then router component must return Page element:

    1. <template>
    2. <div class="page">
    3. ...
    4. </div>
    5. </template>
  • If you load modal (Routable Modals) as router component then router component must return that modal element:

    1. <template>
    2. <div class="popup">
    3. ...
    4. </div>
    5. </template>
  • If you load panel (Routable Panels) as router component then router component must return Panel element:

    1. <template>
    2. <div class="panel panel-left panel-cover">
    3. ...
    4. </div>
    5. </template>
  • If you load tab content (Routable Tabs) as router component then router component must return Tab’s child element that will be inserted inside of routable Tab:

    1. <template>
    2. <div class="some-element">
    3. ...
    4. </div>
    5. </template>

Single File Component

It is not very comfortable to specify all component routes under same routes array, especially if we have a lot of such routes. This is why we can use componentUrl instead and out component into single file:

  1. routes = [
  2. ...
  3. {
  4. path: '/some-page/',
  5. componentUrl: './some-page.html',
  6. },
  7. ..
  8. ];

And in some-page.html:

  1. <!-- component template -->
  2. <template>
  3. <div class="page">
  4. <div class="navbar">
  5. <div class="navbar-inner">
  6. <div class="title">{{title}}</div>
  7. </div>
  8. </div>
  9. <div class="page-content">
  10. <a @click="openAlert">Open Alert</a>
  11. <div class="list simple-list">
  12. <ul>
  13. {{#each names}}
  14. <li>{{this}}</li>
  15. {{/each}}
  16. </ul>
  17. </div>
  18. </div>
  19. </div>
  20. </template>
  21. <!-- component styles -->
  22. <style>
  23. .red-link {
  24. color: red;
  25. }
  26. </style>
  27. <!-- rest of component data and methods -->
  28. <script>
  29. // script must return component object
  30. return {
  31. data: function () {
  32. return {
  33. title: 'Component Page',
  34. names: ['John', 'Vladimir', 'Timo'],
  35. }
  36. },
  37. methods: {
  38. openAlert: function () {
  39. var self = this.$app.dialog.alert('Hello world!');
  40. },
  41. },
  42. on: {
  43. pageInit: function () {
  44. // do something on page init
  45. },
  46. pageAfterOut: function () {
  47. // page has left the view
  48. },
  49. }
  50. }
  51. </script>

Well, now it is much cleaner. The <template> and <style> tags will be automatically converted to the same properties of exported component.

You may think that it is not valid to have a direct return statement in script, but it is ok because parser puts the content of the script tag into function body.

ES Template Literals

The feature available from Framework7 version 3.1.0.

When we use single file component, the everything what is under <template> tag is compiled as Template7 template. In some situations it may bring more complexity, if you need to do a lot of complex checks and modifications right in the template. With Template7 you may need to register a bunch of helpers.

So single file component template can be treated as native JavaScript Template literal.

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called “template strings” in prior editions of the ES2015 specification.

  1. var a = 5;
  2. var b = 10;
  3. console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);

To enable your component template being treated as template literal we need to add es attribute to <template> tag. The template from previous example will look like:

  1. <template es>
  2. <div class="page">
  3. <div class="navbar">
  4. <div class="navbar-inner">
  5. <div class="title">${this.title}</div>
  6. </div>
  7. </div>
  8. <div class="page-content">
  9. <a @click="openAlert">Open Alert</a>
  10. <div class="list simple-list">
  11. <ul>
  12. ${this.names.map((name) => `
  13. <li>${name}</li>
  14. `).join('')}
  15. </ul>
  16. </div>
  17. </div>
  18. </div>
  19. </template>

Scoped Styles

In case you want to scope component styles in single file component to this component only, you may add **scoped** attribute to component <style> tag:

  1. <template>
  2. <!-- component template -->
  3. </template>
  4. <!-- style has additional "scoped" attribute -->
  5. <style scoped>
  6. p {
  7. color: red;
  8. }
  9. a {
  10. text-decoration: none;
  11. }
  12. </style>
  13. <script>
  14. return {
  15. ...
  16. }
  17. </script>

When scoped style added component element will have additional data-f7-[unique_id] where [unique_id] is the unique timestamp. And all styles will be refactored to have this unique scope id, for example:

  1. [data-f7-3454d941c3] p {
  2. color: red;
  3. }
  4. [data-f7-3454d941c3] a {
  5. text-decoration: none;
  6. }

In case you need to use more complex selector with including component parent reference, then you may use **{{this}}** keword to reference the component:

  1. <template>
  2. <!-- component template -->
  3. </template>
  4. <!-- style has additional "scoped" attribute -->
  5. <style scoped>
  6. /* all paragraphs in this component will be red under iOS theme */
  7. html.ios {{this}} p {
  8. color: red;
  9. }
  10. /* all paragraphs in this component will be green under MD theme */
  11. html.md {{this}} p {
  12. color: green;
  13. }
  14. </style>
  15. <script>
  16. return {
  17. ...
  18. }
  19. </script>

Usage With WebPack

There is a special framework7-component-loader for WebPack that allows to bundle Single-File Components into main bundle and not to use XHR (e.g. componentUrl) to load and parse component files each time.

This loader parses Single-File component’s file and transforms it to plain JS object during bundling process. So, potentially, it can increase app performance because there won’t be runtime parsing and compilation.

When this loader is configured, we need to store Single-File components in **.f7.html** files and use export default for component export:

  1. <template>
  2. <div class="page">
  3. ...
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. foo: 'bar',
  11. }
  12. },
  13. methods: {
  14. doThis() {
  15. // ...
  16. }
  17. }
  18. }
  19. </script>

It also possible to import required dependencies and styles:

  1. <template>
  2. <div class="page">
  3. ...
  4. </div>
  5. </template>
  6. <script>
  7. import './path/to/some-styles.css';
  8. import utils from './path/to/utils.js';
  9. export default {
  10. data() {
  11. return {
  12. foo: 'bar',
  13. now: utils.now(),
  14. }
  15. },
  16. methods: {
  17. doThis() {
  18. // ...
  19. }
  20. }
  21. }
  22. </script>

And then we can import it and add to routes:

  1. // routes.js
  2. import NewsPages from './path/to/news.f7.html';
  3. import ServicePages from './path/to/services.f7.html';
  4. export default [
  5. {
  6. path: '/news/',
  7. component: NewsPages,
  8. },
  9. {
  10. path: '/services/',
  11. component: ServicesPages,
  12. }
  13. ]

Virtual DOM

Virtual DOM and all VDOM related features available from Framework7 version 3.1.0.

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM. It allows us to express our application’s view as a function of its state.

VDOM library called Snabbdom because it is extremely lightweight, fast and fits great for Framework7 environment.

So how does Framework7 router component VDOM rendering works? Component template is converted to VDOM instead of directly inserting to DOM. Later, when component state changes, it creates new VDOM and compares it with previous VDOM. And based on that diff it patches real DOM by changing only elements and attributes that need to be changed. And all this happens automatically!

Let’s look at that user profile component example that will auto update layout when we request user data:

  1. <template>
  2. <div class="page">
  3. <div class="navbar">
  4. <div class="navbar-inner">
  5. <div class="title">Profile</div>
  6. </div>
  7. </div>
  8. <div class="page-content">
  9. {{#if user}}
  10. <!-- Show user list when it is loaded -->
  11. <div class="list simple-list">
  12. <ul>
  13. <li>First Name: {{user.firstName}}</li>
  14. <li>Last Name: {{user.lastName}}</li>
  15. <li>Age: {{user.age}}</li>
  16. </ul>
  17. </div>
  18. {{else}}
  19. <!-- Otherwise show preloader -->
  20. <div class="block block-strong text-align-center">
  21. <div class="preloader"></div>
  22. </div>
  23. {{/if}}
  24. </div>
  25. </div>
  26. </template>
  27. <script>
  28. return {
  29. data: function () {
  30. return {
  31. // empty initial user data
  32. user: null,
  33. }
  34. },
  35. on: {
  36. pageInit: function () {
  37. var self = this;
  38. var app = self.$app;
  39. // request user data on page init
  40. app.request.get('http://api.website.com/get-user-profile', (user) => {
  41. // update component state with new state
  42. self.$setState({
  43. user: user,
  44. });
  45. });
  46. },
  47. },
  48. };
  49. </script>

Note, that direct assignment to component state won’t trigger layout update. And if we in previous example used this.user = user it wouldn’t be updated. Use $setState whenever you need to update component layout!

Keys in Lists & Auto-Init Components

When VDOM is updating a list of elements, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, it will patch each element in-place and make sure it reflects what should be rendered at that particular index.

This default mode is efficient, but only suitable when your render output does not rely on child component state or temporary DOM state (e.g. form input values).

To give VDOM a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item.

When rendering lists, an ideal value for key would be the unique id of each item:

  1. <template>
  2. ...
  3. <ul>
  4. {{#each items}}
  5. <li key="{{this.id}}">...</li>
  6. {{/each}}
  7. </ul>
  8. ...
  9. </template>
  10. <script>
  11. return {
  12. data: function () {
  13. return {
  14. items: [
  15. {
  16. id: 1,
  17. title: 'Item A'
  18. },
  19. {
  20. id: 2,
  21. title: 'Item B'
  22. },
  23. ]
  24. }
  25. }
  26. }
  27. </script>

Same with auto-initialized components like Range Slider, Gauge and others that should be automatically initialized (if they have range-slider-init, gauge-init) when they added to DOM, and automatically destroyed when they removed from DOM. So such elements must be also indentified with unique keys.

  1. <template>
  2. <div class="page">
  3. ...
  4. <div class="page-content">
  5. {{#if gaugeVisible}}
  6. <!-- must have unique key -->
  7. <div key="gauge" class="gauge gauge-init" data-type="circle"
  8. data-value="0.60"
  9. data-value-text="60%"
  10. data-value-text-color="#ff9800"
  11. data-border-color="#ff9800"
  12. ></div>
  13. {{/if}}
  14. ...
  15. <a href="#" class="button" @click="showGauge">Show Gauge</a>
  16. </div>
  17. </div>
  18. </template>
  19. <script>
  20. return {
  21. data: function () {
  22. return {
  23. gaugeVisible: false,
  24. }
  25. },
  26. methods: {
  27. showGauge: function () {
  28. this.$setState({
  29. gaugeVisible: true
  30. })
  31. },
  32. }
  33. }
  34. </script>
  • Note that key attribute must be unique accross single component.
  • If key attribute was not specified and element has an id attribute, then id attribute will be used as virtual node unique key.