Components

Introduction

EJS supports custom, reusable components by leveraging the VueJS library. A component is simply a self-contained triad of HTML, JavaScript, and CSS that can be represented by a custom HTML tag.

Check out the VueJS documentation for more information on using components.

Single-file Components

EJS provides on-the-fly code-splitting and compilation of VueJS components defined in a single file. This allows the component author to include the entire component definition in one file.

Syntax

Single-file components are defined using simple HTML syntax in a file with a .vue extension.

MyComponent.vue
<template>
    <div class="my-component">I'm a component template!</div>
</template>

<script>
    module.exports = {
        name: 'my-component'
    };
</script>

<style>
    .my-component {
        width:100%;
        color:blue;
    }
</style>

Known Limitations

EJS does not currently support scoped or pre-processed CSS in component definitions.

Instance methods

The EJS environment makes several instance methods available within component definitions. These methods provide access to core functionality, such as routing and translations.

All instance methods are available as properties on this within a component and are prefixed with the dollar symbol ($).

$getRoute() : CompiledRoute

The $getRoute() instance method returns a compiled route object, representing the route currently matched in the address bar.

The compiled route object is useful for looking up matched parameter values, reading metadata from the route definition, and determining the relative position in the routing tree.

$generatePath(string routeName, Object params) : string

The $generatePath instance method makes it possible to generate the absolute path to any route using its name and parameters. Using this method ensures all links are automatically updated whenever a route is changed.

Alternatively, you may use a view link within your component templates to generate routes declaratively.

$translate(string stringId, Object args) : string

The $translate instance method provides access to translations from the internationalization library. It accepts the identifier for a string resource and an object containing key-value pairs representing variables to replace in the processed string.

The translations are performed based on the currently set active locale.

$setLocale(string localeCode) : void

The $setLocale instance method is used to set the active locale. Changing the active locale automatically loads the appropriate language packs and performs all necessary translations.

Last updated