Last update on Sunday, January 21st 2018

Using Vue with Ionic 4 and Ionic Native Plugins

We used the Cordova CLI to create an Ionic Vue mobile application in the previous tutorial.
This time we will use the Ionic CLI to bootstrap our application.

Let’s create the Ionic application:

ionic start ionic-vue blank

And grab the required libraries:

ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
npm install --save @ionic-native/geolocation

The biggest advantage of this stack is the Webpack implementation (production builds, TypeScript, etc.) the Ionic team created for us.

If you are familiar with the Ionic Build Process, you must know that our TypeScript code will be compiled to a main.js file then called in the index.html file:

  <!-- The main bundle js is generated during the build process -->
  <script src="build/main.js"></script>

If this is still blurry for you, you can have a look at the Ionic build process tutorial.

Here is the final JavaScript code of this tutorial:

webpackJsonp(
  [0],
  {
    /***/ 17: /***/ function(module, exports) {
      function webpackEmptyAsyncContext(req) {
        // Here Promise.resolve().then() is used instead of new Promise() to prevent
        // uncatched exception popping up in devtools
        return Promise.resolve().then(function() {
          throw new Error("Cannot find module '" + req + "'.");
        });
      }
      webpackEmptyAsyncContext.keys = function() {
        return [];
      };
      webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
      module.exports = webpackEmptyAsyncContext;
      webpackEmptyAsyncContext.id = 17;

      /***/
    },

    /***/ 19: /***/ function(module, __webpack_exports__, __webpack_require__) {
      "use strict";
      Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
      /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__ionic_native_geolocation__ = __webpack_require__(
        20
      );

      var geolocation = new __WEBPACK_IMPORTED_MODULE_0__ionic_native_geolocation__[
        "a" /* Geolocation */
      ]();
      Vue.config.ignoredElements = ["ion-card", "ion-card-content"];
      var app = new Vue({
        el: "#app",
        data: {
          loadingPosition: false,
          geolocation: {}
        },
        methods: {
          getPosition: function() {
            var _this = this;
            this.loadingPosition = true;
            geolocation.getCurrentPosition().then(function(_a) {
              var coords = _a.coords;
              _this.loadingPosition = false;
              _this.geolocation = coords;
            });
          }
        }
      });
      //# sourceMappingURL=main.js.map

      /***/
    }
  },
  [19]
);
//# sourceMappingURL=main.js.map

Project Clean up

The current Ionic stack is oriented toward Angular.
There are many files and folders we don’t need.

Here is a normal Ionic Angular architecture:

Ionic Vue Ionic Native Geolocaiton more files

And we can reduce ours to this:

Ionic Vue Ionic Native Geolocation less files

The app.component.ts and app.module.ts files are both useless, however, we can’t remove them because the Ionic CLI checks for those files during the build process.

The Code

We can now go to the index.html and use the same template we used in the previous tutorial:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <!-- cordova.js required for cordova apps (remove if not needed) -->
  <script src="cordova.js"></script>

  <script src="https://unpkg.com/vue"></script>
  <script src="https://unpkg.com/@ionic/[email protected]/dist/ionic.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>

<body>

  <!-- Ionic's root component and where the app will load -->

  <div id="app">
    <button @click="getPosition()">
       Get Position
    </button>

    <ion-card>

      <ion-card-content>

        <div v-if="geolocation.latitude">
          You are located at: {{geolocation.latitude}}, {{geolocation.longitude}}
        </div>

        <div v-else-if="loadingPosition">
          Acquiring your position
        </div>

        <div v-else>
          Tap the button
        </div>

      </ion-card-content>

    </ion-card>
  </div>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The main bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>

We still use the unpkg service to acquire the Vue and Ionic 4 libraries.
The application should trigger an error about the missing ion-app element.

To prevent this, we can modify the main.js file.
This is where we will bootstrap our Ionic Vue application:

declare var Vue: any;

import * as GeolocationService from "@ionic-native/geolocation";

const geolocation = new GeolocationService.Geolocation();

Vue.config.ignoredElements = ["ion-card", "ion-card-content"];

We are working with TypeScript.
We need to declare the Vue variable with the type any, otherwise the TypeScript compiler won’t be happy.

We then acquire the Ionic Native Geolocation API.
We are not in an Angular application anymore and can’t use the Dependency Injection System. Creating a new geolocation instance will do the job.

The rest of the code is similar to the one from the previous tutorial:

Vue.config.ignoredElements = ["ion-card", "ion-card-content"];

var app = new Vue({
  el: "#app",
  data: {
    loadingPosition: false,
    geolocation: {}
  },
  methods: {
    getPosition: function() {
      this.loadingPosition = true;

      geolocation.getCurrentPosition().then(({ coords }) => {
        this.loadingPosition = false;
        this.geolocation = coords;
      });
    }
  }
});

The only modification here is the geolocation’s getCurrentPosition method. This one is from the Ionic Native Geolocation API which returns a Promise that contains the coords field.

And Voila!

Typing:

ionic cordova run ios

Our Ionic Vue mobile application is running on a device as expected:

Ionic Vue Cordova final geolocation result

Conclusion

At the moment we are stuck with an Angular architecture. The incoming Ionic CLI will most likely ask us which technology we would like to use, letting us choose between Angular, Vue, React, Vanilla JavaScript, etc.
Using the Ionic CLI to create an Ionic 4 Vue mobile application is quite simple, we only need to add two external libraries, delete some Angular oriented files and that's it!
Our project is ready to roll on a mobile device!

Using Vue with Ionic 4 and Cordova Plugins

Vue as an Angular alternative for Ionic: The Components

Using Vue as an Angular alternative for Ionic: The Directives

Stay up to date


Join over 4000 other developers who already receive my tutorials and their source code out of the oven + other free stuff!