Starting Project

Note: For more details to use Onsen UI in your project, please refer to Getting Started.

To use Onsen UI in Vue 2 apps, Onsen UI Core and Vue 2 Components should be installed to the project. These modules can be installed via NPM package: onsenui and vue-onsenui.

To quickly setup the project, Monaca CLI will solve all dependencies including TypeScript, Webpack and polyfills if necessary.

Using Onsen UI toolkit - Monaca CLI

$ npm install -g monaca # Install Monaca CLI - Onsen UI toolkit
$ monaca create helloworld # Choose Vue 2 template
$ cd helloworld; monaca preview # Run preview, or "monaca debug" to run on your device

Download via npm

$ npm install onsenui vue-onsenui --save-dev

Direct download

Get onsenui.js, onsenui.css and onsenui-css-components.css from the latest core release. You will also need vue-onsenui.js file from this CDN link.

Loading Onsen UI

Vue bindings for Onsen UI (VueOnsen) provide Vue 2 components and directives that wrap the core Web Components and expose a Vue-like API to interact with them. You need to load the following two JavaScript modules:

You can load with normal <script></script> and <link> tags as follows:

<link rel="stylesheet" href="onsenui.css">
<link rel="stylesheet" href="onsen-css-components.css">

<script src="vue.js"></script>
<script src="onsenui.js"></script>
<script src="vue-onsenui.js"></script>

Or, you can use VueOnsen from npm with a module bundler like Webpack. In this case, use the onsenui and vue-onsenui packages.

// Webpack CSS import
import 'onsenui/css/onsenui.css';
import 'onsenui/css/onsen-css-components.css';

// JS import
import Vue from 'vue';
import 'onsenui';
import VueOnsen from 'vue-onsenui';

Vue.use(VueOnsen);

Notice how VueOnsen is used as a plugin for Vue in the last line (this is already done automatically if window.Vue exists). Alternatively, you can use require instead of ES6 imports.

Onsen UI HelloWorld with Vue

To get started, let’s create a simple Hello World application. The following sample code is a Vue version of Onsen UI HelloWorld.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="onsenui.css">
    <link rel="stylesheet" href="onsen-css-components.css">
    <script src="vue.js"></script>
    <script src="onsenui.js"></script>
    <script src="vue-onsenui.js"></script>
  </head>
  <body>
    <template id="main-page">
      <v-ons-page>
        <v-ons-toolbar>
          <div class="center">Title</div>
        </v-ons-toolbar>
        <p style="text-align: center">
          <v-ons-button @click="$ons.notification.alert('Hello World!')">Click</v-ons-button>
        </p>
      </v-ons-page>
    </template>

    <div id="app"></div>
  </body>
  <script>
    var vm = new Vue({
      el: '#app',
      template: '#main-page'
    });
  </script>
</html>

This example is loading the following JS libraries, vue.js, onsenui.js and vue-onsenui.js. For stylesheets, it is loading onsenui.css and onsen-css-components.css which are bundled in Onsen UI distribution package. To know the details about Onsen UI stylesheets, please refer to our Style Sheets Guide document.

<link rel="stylesheet" href="path/to/onsenui.css">
<link rel="stylesheet" href="path/to/onsen-css-components.css">

The <div id="app"></div> node is where Vue will render the content into (el property in the constructor).

This is a pure ES5 example, although normally it’s advisable to use ES2015 and vue-loader since it allows *.vue format. For consistency, from now on we will write every Vue component example following the aforementioned format.

For more information about Vue, we recommend to read the official Vue docs.

Creating a page

The root of a page is created using the <v-ons-page> component. It covers the whole screen and is used as a container for the other components.

Adding a toolbar

A toolbar is defined as a <v-ons-toolbar> or <v-ons-bottom-toolbar> component. Here is the typical example of a toolbar.

<v-ons-page>
  <v-ons-toolbar>
    <div class="left">
      <v-ons-back-button>Back</v-ons-back-button>
    </div>
    <div class="center">Title</div>
    <div class="right">
      <v-ons-toolbar-button>
        <v-ons-icon icon="md-menu"></v-ons-icon>
      </v-ons-toolbar-button>
    </div>
  </v-ons-toolbar>

  Some other content...
</v-ons-page>

The toolbar is divided into 3 sections that can be specified as class names (left, center, and right). You can use <v-ons-icon> to display an icon, <v-ons-toolbar-button> or <v-ons-back-button> to place an button, or insert any HTML content.

Event Handling

Onsen UI components are capable of handling events. For instance, you can catch a tap event by using the @click handler, or text input change with the @input handler.

 <v-ons-input @input="..." type="text"></v-ons-input>
 <v-ons-input @change="..." type="checkbox"></v-ons-input>
 <v-ons-button @click="..."></v-ons-button>
 <v-ons-navigator @prepop="..."></v-ons-navigator>
 <v-ons-page @deviceBackButton="..."></v-ons-page>

The $ons object

Onsen UI not only provides custom components, it also exposes an object called $ons with a lot of useful functions attached to it. The $ons object is part of the core library and can be imported in the bindings.

The following example uses $ons.ready(fn) which waits until the app is completely loaded before executing a callback function. Inside the callback, it is calling $ons.notification.alert() to display a alert dialog.

$ons.ready(function() {
  // Onsen UI is now initialized
  $ons.notification.alert('Welcome to Onsen UI!');
});

See also $ons.platform, $ons.notification and $ons.orientation for more utilities.

Understanding Vue Components

Having a general idea about how everything is implemented could be useful in some situations. This is a brief explanation about how Vue Componentes for Onsen UI work.

These components are simple wrappers around inner Custom Elements in most of the cases. This means that a Vue Component takes some props and translate them into DOM properties, DOM attributes or method calls for the Onsen UI core. It also listens for native events and fires the corresponding Vue events. If you inspect the DOM you will likely see a bunch of ons-* components without v-* prefix (these are real HTMLelements). You can have a look at the implementation here.

Adding page content

For a full list of components please check the reference page.

Form components

Onsen UI provides a rich set of form components. Apart from <v-ons-button>, <v-ons-switch>,<v-ons-select> and <v-ons-range>, perhaps the <v-ons-input> component is the most common one since it supports different shapes: checkbox, radio, password, etc.

<v-ons-page>
  <v-ons-toolbar>
    <div class="center">Form</div>
  </v-ons-toolbar>
  <div style="text-align: center; margin-top: 30px;">
    <p><v-ons-input type="text" placeholder="Username" float></v-ons-input></p>
    <p><v-ons-input type="password" placeholder="Password" float></v-ons-input></p>
    <p><v-ons-button>Sign in</v-ons-button></p>
  </div>
</v-ons-page>

Lists

Lists are a very common pattern in mobile apps and thus Onsen UI provides abstraction for it. By using <v-ons-list>, <v-ons-list-item> and <v-ons-list-header> you can make simple or complex lists of items. Every list item is by default divided into three sections, just like <v-ons-toolbar>, and some CSS classes are provided for default styles (list-item__icon, list-item__thumbnail, list-item__title and list-item__subtitle).

<v-ons-list>
  <v-ons-list-header>Header</v-ons-list-header>
  <v-ons-list-item>
    <div class="left">
      <v-ons-icon icon="md-face" class="list-item__icon"></v-ons-icon>
    </div>
    <div class="center">
      <span class="list-item__title">Title</span>
      <span class="list-item__subtitle">Subtitle</span>
    </div>
    <label class="right">
      <v-ons-switch></v-ons-switch>
    </label>
  </v-ons-list-item>
  ...
</v-ons-list>
Infinite scroll

Adding new items to the list whenever the user reaches the bottom of the list is a very common practice. This use case is covered in <v-ons-page> component.

An infiniteScroll prop can be specified in order to pass a function handler.

Lazy repeat

For cases when the list can contain thousands of items, <v-ons-lazy-repeat> component will enhance the performance by loading and unloading items depending on the current scroll.

Layouting

Onsen UI provides a grid system to place your components in the screen. The grid system divides the screen into rows and columns, just like a spreadsheet. The width and height of each grid is adjustable, and you can also condense two or more grids in a row or column, into one grid.

The layout can be performed by combining <v-ons-col> and <v-ons-row> components. The width and height can be adjusted in a flexible way.

Grid is not necessary in general for list items. Special layout is provided for list items based on flat iOS and Material Design specification. See list section for more information.

Control and visual components

Other components from different categories are available to complete the developer needs.

<v-ons-carousel> and <v-ons-carousel-item> components provide a simple carousel that can optionally be overscrollable and fullscreen.

Pull-hook

A very common way to check to get updates in apps is given by the <v-ons-pull-hook> component, which enables a simple “pull to refresh” functionality.

Speed-dial

<v-ons-speed-dial> and <v-ons-speed-dial-item> are just a set of floating action buttons (<v-ons-fab>) that can be shown or hidden by the user. This components are mainly used in Material Design.

Progress

<v-ons-progress-bar> and <v-ons-progress-circular> display the loading progress like it’s done in Material Design. Two modes are supported: display the exact progress that is provided to the component or display an indeterminated progress.

Icons

Onsen UI bundles three icon packs to be used with <v-ons-icon> component:

In general, Ionicons are good for iOS apps while the Material Icons work best for apps using Material Design.

Gesture detector

It is a common use case to detect a finger gesture and do a specific task. Onsen UI utilizes a modified version of Hammer.js for gesture detection. The Gesture Detector class (Hammer.js) is exposed in $ons.GestureDetector object.

var divGD = $ons.GestureDetector(document.querySelector('#my-div'));
divGD.on('dragup dragdown', function(event) {
  console.log('drag Y axis');
});

If you want to use another library for this purpose and have any conflict, Onsen UI gesture detectors can be disabled easily:

$ons.GestureDetector(document.querySelector('#my-menu')).dispose(); // Remove event listeners from the menu

Also, <v-ons-gesture-detector> component can be used to wrap the target DOM component that should detect the fingers in a handy way.

VOnsModel Directive

Vue offers a very handy v-model directive for input element. Unfortunately, v-model is not fully extendable (not even with the update in Vue 2.2.0) and features like using an array with checkboxes do not work with custom UI components. Therefore, Onsen UI implements v-ons-model directive that can be used with Onsen UI inputs (v-ons-input of any type, v-ons-switch, v-ons-range and v-ons-select). It emulates the original behavior of v-model, making it possible again to assign arrays or booleans to checkboxes and switches, for example. The value passed to v-ons-model should be either a literal value (initial value) or the name of a variable in the current context: <v-ons-input v-ons-model="myValue"></v-ons-input>. Currently, it does not support syntax like v-ons-model="container['value']". Use dot notation instead: v-ons-model="container.value".

Dialogs

There are multiple types of dialog components available in Onsen UI: <v-ons-dialog> for displaying a page inside a centered dialog; <v-ons-alert-dialog> for displaying a simple message inside an alert style dialog; <v-ons-popover> for showing some content next to a specified component or a context menu; <v-ons-toast> for displaying a dismissable short message at the bottom or top of the page; <v-ons-action-sheet> (bottom sheet in Material Design) for letting users choose among a list of options that comes from the bottom side; and <v-ons-modal> for displaying a fullscreen dialog that forbids user interaction.

Apart from that, $ons object offers a more handy solution for simple dialogs:

$ons.notification.alert('Hello world!'); // Basic alert
$ons.notification.confirm('Are you ready?'); // OK - Cancel buttons
$ons.notification.prompt('What is your name?'); // Text input
$ons.notification.toast('New password saved.'); // Toast - Snackbar

$ons.openActionSheet({ title: 'Actions', buttons: ['Copy', 'Cut', 'Delete'] }); // Options list

Multiple page navigation

In Onsen UI there are three navigation patterns based on three different components: <v-ons-navigator>, <v-ons-tabbar> and <v-ons-splitter>. These components supply “frames” able to change their inner content. The content of these frames will normally be <v-ons-page> components but it is also possible to nest navigation components in order to combine them.

More information is provided in the “Docs” tab of the Live Example section of each component.

The main pattern uses <v-ons-navigator> component to provide a stack where you can push and pop pages with transition animations. This is the basic and most used navigation pattern and can be combined with the other two.

Use this pattern when you have a sequential flow where a page depends on the previous one. Data can be optionally passed from one page to another.

Tabbar

In this case, by using <v-ons-tabbar> component a visible tabbar is displayed at the bottom or the top of the page with tabs associated to different pages. The component will load content depending on the selected tab (<v-ons-tab>). This pattern is commonly used to sepparate different sections in the app.

A menu can be added using the <v-ons-splitter> component. For small devices it can be used to create a swipeable menu, but for larger screens it can automatically display a column layout.

Splitter provides two frames that can load different content: <v-ons-splitter-side> and <v-ons-splitter-content>. A common usecase is to show a list in the side menu where each item loads a different page in the content frame. Notice that loading new content in any of these frames will completely remove the previous loaded content. For more complex navigation consider nesting <v-ons-navigator> inside <v-ons-splitter-content>.

Preventing Default Behavior

Sometimes it can be useful to prevent Onsen UI’s default behavior on user interaction in order to use some Vue features. For example, a v-ons-tabbar could work with <keep-alive> component if v-ons-tab on click behavior is properly overriden.

Another example could be the click/tap behavior of v-ons-back-button. Instead of popping 1 page, it can be overriden to reset the page stack (going back to “home” page). All of these default behaviors can be prevented by running $event.preventDefault() in the corresponding event handlers or providing Vue’s prevent modifier in the event listeners. More information in the reference page of each component.

Using Modifier

Modifier is a cross-component way to provide customizability for Onsen UI components. When a component is defined with a modifier, it will have a separate class namespace so that you can apply custom styles to the component. Also, some components have several preset modifiers to change the appearance.

For example, each of the following buttons have different look. To change modifiers dynamically, please manipulate modifier attribute from JavaScript.

<v-ons-button modifier="quiet">Quiet</v-ons-button>
<v-ons-button modifier="light">Light</v-ons-button>
<v-ons-button modifier="large">Large</v-ons-button>
<v-ons-button modifier="cta">Call To Action</v-ons-button>
<v-ons-button modifier="material">Material Design</v-ons-button>

Cross platform styling

Onsen UI components are automatically styled depending on the platform where the app runs. You can easily test this feature with your browser Dev Tools by switching between iOS and Android views.

Automatic styling simply applies modifier="material" to the components when $ons.platform.isAndroid() is true. You can disable this feature by running $ons.disableAutoStyling() right after including onsenui.js (i.e. before the app is initialized). If you disable it you may need to manually specify modifier="material" in every component you want to display with Material Design. You can also specify disable-auto-styling attribute in specific components that you don’t want to auto style.

Some tools are provided to give a more accurate customization.

Platform utilities

$ons.platform object is available with methods such as $ons.platform.isIOS(), $ons.platform.isWebView(), etc.

You can set a platform with $ons.platform.select('android'), for example, in order to display Material Design on every platform. This must be called before the app is initialized (right after including onsenui.js).

With this, for example, you can display <v-ons-fab> for Material Design and other type of button for iOS flat design.

Icons shortcut

<v-ons-icon> component provides a shortcut to make auto styling easier:

<v-ons-icon icon="ion-navicon, material:md-menu" size="24px, material:20px"></v-ons-icon>

The second icon will be displayed when material modifier is present (other modifiers can be used).

CSS Definitions

Onsen UI styles are defined in onsenui.css and onsen-css-components.css. They are written in pure CSS using some extra features provided by cssnext.

onsenui.css is a core CSS module that defines styles for the custom components. The source code exists under core/css directory. onsen-css-components.css contains CSS definitions for CSS components. The source code exists in css-components/src.

A local tool is included in Onsen UI core (onsenui) for previewing changes in Onsen CSS Component. This tool, located under onsenui/css-components-src/ directory in a local instalation, is also able to generate a new onsenui-css-components.css file that must be imported in the project.

Overriding CSS style

If you want to apply a different style to a specific component, you can use modifier attribute to override its style definition.

For example, if you want to apply a thick border only to a specific button, you can define like the one below.

<v-ons-button modifier="thick">Thick Button</v-ons-button>

Then, write the appropriate style code under the style tag or in the css file.

<style>
.button--thick {
  border: 10px;
}
</style>

Device Back Button

For Android devices, Cordova fires a backbutton event on hardware back button. It is important to understand that this event is fired by Cordova so it requires cordova.js file or similars (loader.js in Monaca) to be included in the app. Since it cannot be tested in browsers without Cordova, you can use Monaca Debugger for this purpose.

Onsen UI sets handlers with default behavior for Android back button in certain components:

If the conditions are not met, these components will call the parent component’s handler. The final global handler closes the app.

While this is probably the desired behavior for many apps, Onsen UI allows to modify these handlers for better customization. To modify the app global handler (closing the app), the $ons object provides few methods:

// Disable or enable
$ons.disableDeviceBackButtonHandler();
$ons.enableDeviceBackButtonHandler();

// Set a new handler
$ons.setDefaultDeviceBackButtonListener(function(event) {
  $ons.notification.confirm('Do you want to close the app?') // Ask for confirmation
    .then(function(index) {
      if (index === 1) { // OK button
        navigator.app.exitApp(); // Close the app
      }
    });
});

Apart from this, the mentioned components together with v-ons-page component expose a way to modify their own handler:

<v-ons-page @deviceBackButton="..."></v-ons-page>
<v-ons-navigator @deviceBackButton="..."></v-ons-page>
<v-ons-dialog @deviceBackButton="..."></v-ons-page>

The default behavior of each component can be prevented (and overriden) by running $event.preventDefault() or using the prevent modifier shorthand for event listeners in Vue:

<v-ons-navigator @deviceBackButton.prevent="resetPageStack()"></v-ons-page>

The event object provided to this handler also contains a event.callParentHandler() method.

Extending animations

Onsen UI already provides multiple built-in animations for its routing components and dialogs. However, it is also possible to create custom animations for specific components or even extend existing animations and change part of them. This is a relatively advanced topic since it requires digging a bit in Onsen UI core code.

Animit

Onsen UI relies on Animit, a minimal animation library for managing CSS transtions on mobile browsers.

Animit can be accessed with $ons.animit or import { animit } from ons;, depending on the type of the app. It exposes methods to queue CSS animations, apply delays and run callbacks as follows:

let animation1 = animit(myElement) // This defines the animation for the provided component
  .saveStyle() // Saves the original style of the component
  .queue({ // Original position/style in the animation
    css: {
      transform: 'translate3D(0, 100%, 0)'
    },
    duration: 0
  })
  .wait(0.2) // Delay applied before the transition starts
  .queue({ // Next step in the animation
    css: {
      transform: 'translate3D(0, 0, 0)',
    },
    duration: 0.6,
    timing: 'linear'
  })
  .restoreStyle() // Restores the original style of the component
  .queue(done => { // Optional "On transition end" callback
    callback();
    done();
  }
);

animation1.play(); // Run the animation

Since Animit modifies the component’s style property, it provides saveStyle() and restoreStyle() methods to ensure the previous styles are not lost. queue({css: {...}, duration: 0, timing: 'linear'}) or queue({...}, {duration: 0, timing: 'linear'}) method is provided to add transitions to the queue. The first one will be the first style applied in the animation that will transition into the following styles. In the provided example, we are moving a new page inside the view from right to left. Therefore, it needs to start at position translate3d(0, 100%, 0) and move to translate3d(0, 0, 0). Method wait(...) can be used to apply a delay between transitions. Finally, we can optionally call queue(function(done) { ...; done(); }) again to run a callback if necessary.

It is also possible to pass an array of HTML components to animit if performing the same animation on multiple components is required: animit([el1, el2]).saveStyle()....

It is very common to have more than one animation running at the same time. animit.runAll(animation1, animation2, animation3); method can be used for this behavior instead of animation1.play(); animation2.play(); animation3.play();.

Creating animators

Animators can be created from scratch by extending the necessary animator classes that Onsen UI provides. Every component exposes a minimum animator interface that must be extended and implemented: NavigatorTransitionAnimator, AlertDialogAnimator, DialogAnimator, PopoverAnimator, ModalAnimator, TabbarAnimator and SplitterAnimator. This is the desired way to implement animators if you want to build a custom version of Onsen UI or want to make a pull request to the repository. For more information, please have a look at the existing animators for every component.

ES2015 (ES6) is preffered but not strictly required for this to work. An example in ES5 can be found here.

Extending animators

Another way to make new animators is extending an existing animator and modifiying part of its behavior (or all). This is in general easier if you just want to tweak the appearance or timing, or even if you want to create a whole new thing starting from another animator. For this it is also required to have a look at the existing animators, choose one and check its properties and methods. Every animator provides a extend({...}) class method that returns a new animator. Animators are exposed in every component class: $ons.NavigatorElement.animators or $ons.AlertDialogElement.animators are some examples. These objects contain all the registered animators and can be extended as follows.

var fadeIOS = $ons.NavigatorElement.animators['fade-ios'];
var customAnimator = fadeIOS.extend({
  timing: 'cubic-bezier(.1, .7, .1, 1)',
  delay: 0.1,
  push: function(enterPage, leavePage, callback) {
    $ons.animit.runAll(
      $ons.animit(enterPage)...,
      $ons.animit(leavePage)...
    );
  }
});

// This step is mandatory
$ons.NavigatorElement.registerAnimator('customAnimationName', customAnimator);

This overwrites the push animation but uses the original pop animation. timing and delay properties will still affect both animations. Some animators have extra properties, such as backgroundMask. Please check the animator you want to extend to see all the properties.

After the new animator is created and registered, we can simply specify the animation with its name: myNavigator.pushPage('page.html', {animation: 'customAnimationName'}). Or make it default: <v-ons-navigator animation="customAnimationName">. The same applies to the other components.

Need Help?

If you have any questions, use our Community Forum or talk to us via Gitter chat. The Onsen UI team and your peers in the community will work together to help solve your issues.

For bug reports and feature requests use our GitHub Issues page.