Tutorial

How to Setup, Build and Deploy Native Apps with Vue

JavaScriptVue.js

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

Vue Native is a Javascript framework that is designed to deliver cross platform mobile native applications. It is inspired by the React Native project.

Vue Native was originally a fork from React-vue, a compiler that gave developers that ability to write Vue and React in the same codebase. In this tutorial you will build an application to learn about the APIs and components available in Vue Native.

The application that you build will display trending gifs on the Giphy platform. The Giphy API will be used to get the associated gif image, title and type from for each trending gif. The image and details will be displayed using Vue Native components like ScrollView, Text, and Image.

Prerequisites

To follow this tutorial, you will need to have Node > 6.0 installed. You will also need a Node package manager like NPM (which comes packaged with Node) or Yarn.

Some knowledge of Javascript and Vue is also required. You can follow the official Vue documentation here to become familiar with some fo the core Vue concepts and components.

Getting started

Before getting started, you will need to setup a project and install some dependencies. The Vue native CLI will be used to bootstrap the application.

First, install the Vue Native CLI by running the following command (choose one based on your package manager):

  • yarn global add vue-native-cli
  • // or
  • npm install -g vue-native-cli

Then initialize a new project by running the following command:

  • vue-native init vue-gifs

Running this command will bootstrap an application for this project using the Expo CLI.

At the time of writing the Vue Native CLI needs the React Native version 0.55.4 and expo version 29.0.0, so update your package.json to set these versions. To build for ios and android platforms, update the scripts object like this:

//package.json

{
  "name": "vue-gifs",
  "main": "node_modules/expo/AppEntry.js",
  "private": true,
  "scripts": {
    ...
    "build:ios": "expo build:ios",
    "build:android": "expo build:android",
  },
  "dependencies": {
    "expo": "^29.0.0",
    ...
    "react-native": "0.55.4",
    ...
  },
  "devDependencies": {
    "babel-preset-expo": "^4.0.0",
    ...
  }
}

Then update the sdkVersion in the app.json file to match the expo version. Open the app.json file and update it like the snippet below:

{
  "expo": {
    "name": "vue-gifs",
    "description": "This project is really great.",
    ...
    "sdkVersion": "29.0.0",
    ...
  }
}

Everything else will remain the same. After making these changes, run npm install or yarn to install the required versions for the application. When this is done, run npm start to run the application.

Expo will be used to build and run the new application. Expo is an open source tool-chain built around React Native for building Android and iOS applications. It provides access to the system’s functionality like the Camera and Storage.

Testing on mobile

To test the application on mobile, the expo-cli provides various methods to test the application. The first is using a URL that is generated after running the application. This URL can be visited on your mobile browser to test the application.

Run the npm run start-native command within your project folder to run the application using Expo. Expo typically starts your application on port 19002 so visit (http://localhost:19002) to view the expo dev tools in your browser. Within the dev tools you can send the preview link as an SMS or email to your mobile phone.

Screenshot of a browser previewing the expo development tools

You can select any of the three connection options. An external tunnel, LAN or Local connection. For the local connection, your mobile phone and work PC have to be connection to the same network but the tunnel will work in all cases.

The next testing method that you can use is to download the Expo mobile app. It can be found on both the Apple App store and the Android Play store. On iOS, after installing the app open up your camera and scan the barcode from the browser version of the application to run it on your phone. On Android you can use the Expo app directly to scan the barcode and run the application.

Run any of the following command to test on either platforms:

  • npm start

After starting the application scan the barcode and view the application on the expo app. You should see a view similar to the screenshot below:

Phone screenshot of the example application in Expo

Another option for testing on a mobile device is using an emulator or simulator. Using Android studio or Xcode on macOS, you can boot emulators or simulators for their respective platforms. Download and install the tool for the platform of choice, Xcode for iOS and Android studio for Android. After installation, run any of the following commands to start the application:

  • npm run ios
  • # OR
  • npm run android

Creating a Giphy application

To get started consuming the Giphy API, you’ll need to create or log in to a Giphy account. Create one if you haven’t already. The next step is to create an app on the developer platform. On your developer account dashboard, there is a Create App button. Click it and fill in the details about your application.

Screenshot of Giphy developer account dashboard

After creating the app, your new application should be displayed on your dashboard with an API key. This key will be used when making requests to Giphy

Screenshot of registered applications in Giphy develoepr dashboard

Giphy’s Javascript SDK will be used to make requests to the Giphy service itself. Run the following command to install the package:

  • npm install --save giphy-js-sdk-core

Now your project is ready to consume the Giphy APIs with the help of this SDK.

App component

Open the App.vue file in the root folder and update it like the snippet below:

<template>
    <view>
        <scroll-view class="scroll-view">
           //Todo: Create gif item and header
           <view class="loading-container" :style="{flex: 1, justifyContent: 'center'}" v-if="loading">
              <activity-indicator size="large" color="#0000ff"></activity-indicator>
            </view>         </scroll-view>
    </view>
</template>
<script>
  import Giphy from 'giphy-js-sdk-core';
  const client = Giphy('GIPHY_API_KEY');

  export default {
    name: 'App',
    data() {
      return {
        gifs: [],
        loading: true,
      };
    },
    async created() {
      const response = await client.trending('gifs', {limit: 20});
      this.gifs = response.data;
    },
  };
</script>
<style>
    .scroll-view {
        padding-top: 20px;
        padding-bottom: 30px;
    }
    .loading-container {
        height: 600px;
    }
</style>

In the snippet above, the App component renders a scrollview component that houses the components elements. It only displays an activityindicator, this will be replaced by the list of gifs when the call to the API is complete.

The Giphy client is instantiated using the API key obtained from the developers dashboard. Be sure to replace the placeholder string with the API key. Calling the trending method makes a call to the Giphy trending endpoint. The first provided parameter is gifs: this indicates which trending items should be returned, either gifs or stickers. The second parameter is an object providing optional parameters like the limit, offset, rating and fmt (format).

The only parameter used in this code is the limit parameter, which restricts the results to 20 items. This call is made in the created lifecycle of the component. Finally the gif list is used to render the returned results.

After reloading, the application should display the activity indicator:

Screenshot of a mobile phone showing a loading icon

Creating the gif item component

Each gif item will be displayed using a View component. The View component is an important building block in the framework. It supports layout using flexbox, styling and accessibility. Each item will display the gif, title and type. Create a folder components in the root folder. Within the components directory, create a file named GifItem.vue and add the following code:

// GifItem.vue

<template>
  <view class="container">
    <image class="img" :source="{uri: `${gif.images.original.url}`}" style="max-width:100%;"/>
    <text class="title">{{titleCase(gif.title)}}</text>
  </view>
</template>
<script>
export default {
  name: "GifItem",
  props: ["gif"],
  methods: {
    titleCase(text) {
      const textArray = text.split(" ");
      return textArray
        .map(text => {
          const trimmedText = text.trim();
          return `${trimmedText[0].toUpperCase()}${trimmedText.slice(1)}`;
        })
        .join(" ");
    }
  }
};
</script>
<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}
.img {
  height: 200px;
  width: 300px;
}
.title {
  font-size: 14px;
  font-weight: 500;
  margin-top: 7px;
}
</style>

The Image component will be used to display the source of each gif and the Text component will be used to display the gif title. The Image component takes a source prop which is an object with a uri property.

The titleCase method takes the title of each gif and returns the text in title case, capitalizing the first letter of each word in the text. The GifItem component will take a single prop gif.

Update the App.vue file to include the new GifItem using the the snippet below:

<template>
    <view>
        <scroll-view class="scroll-view">
            <gif-item v-for="gif in gifs" :gif="gif" :key="gif.id" v-if="!loading"/>
            <view class="loading-container" :style="{flex: 1, justifyContent: 'center'}" v-if="loading">
                <activity-indicator size="large" color="#0000ff"></activity-indicator>
            </view>
        </scroll-view>
    </view>
</template>
<script>
  import Giphy from 'giphy-js-sdk-core';
  const client = Giphy('API_KEY');
  import GifItem from './components/GifItem';

  export default {
    name: 'App',
    data() {
      return {
        gifs: [],
        loading: true
      };
    },
    async created() {
      const response = await client.trending('gifs', {limit: 20});
      this.gifs = response.data;
      this.loading = false;
    },
    components: {GifItem}
  };
</script>
<style>
    .scroll-view {
        padding-top: 20px;
        padding-bottom: 30px;
    }
    .loading-container {
        height: 600px;
    }
</style>

When you open the application in the expo app, you’ll see something similar to this screenshot:

Screenshot of a phone showing three gifs vertically stacked in a list

If your local application is not displaying a list of gifs, ensure that your code matches the snippets in this tutorial, and that your Giphy API key is valid.

Header component

Now that the application can retrieve and display a list of trending gifs, let’s include a header to give the application context. The View component will be used to create an area that will act as the header for the application. Create a file called header.vue within the components directory and update it with the code below:

// /components/header.vue
<template>
    <view class="header-container">
        <text class="header">Trending</text>
    </view>
</template>
<script>
  export default {
    name: 'header.vue'
  };
</script>
<style scoped>
    .header-container {
        background-color: rgba(0, 0, 0, 0.05);
        display: flex;
        justify-content: center;
        padding-top: 15px;
        padding-bottom: 15px;
        border-bottom-color: aquamarine;
        border-bottom-width: 1px;
        margin-top: 20px;
    }
    .header {
        font-size: 16px;
        color: black;
        opacity: 0.8;
        font-weight: 600;
        text-align: center;
    }
</style>

Now add the header component to the App component. This will display a header at the top of the application. Update the App.vue file to include the Header component:

<template>
    <view>
        <header/>
        <scroll-view class="scroll-view">
            ...
        </scroll-view>
    </view>
</template>
<script>
  import Giphy from 'giphy-js-sdk-core';
  const client = Giphy('TxuQbNU1nyDBwpqrcib61LxmOzsXTPEk');

  import GifItem from './components/GifItem';
  import Header from './components/header';

  export default {
    name: 'App',
    data() {
     ...
    },
    async created() {
      ...
    },
    components: {GifItem, Header}
  };
</script>
<style>
   ...
</style>

After the application refreshes the header will be added to the top of the application.

Screenshot of a phone showing a Header element with the text 'Trending'

The components provided by Vue Native have done all of the work required to render, order, and display the list of trending gifs.

Deploying the application on Android

The final step in this tutorial is to deploy the application to the Android Play store. First, you will need to update app.json to include Android specific properties. Open the app.json file and update the file to include the `android` field:

{
  "expo": {
    ...
    "android": {
      "package": "com.vue.gifs"
    }
  }
}

The android.package field is a unique value that will represent your package in the app store. You can read more on the package naming convention here. After updating the file, run the npm run build:android command.

  • npm run build:android

This command will present you with a prompt, asking you to provide a keystore or to generate a new one. If you have an existing keystore, you can select this option or let expo generate one for your application.

Screenshot of a terminal showing yarn build:android command and output

After completion, a download link will be generated for your application, clicking on this link will be trigger a download for your apk.

Screenshot showing expo.io download URL

To deploy the downloaded APK to the Android Play Store, visit the Play Console to create an account. You will need to pay a registration fee of $25 before proceeding. When registration is complete, visit this page and follow the steps to upload your application to the Play Store.

Summary

Vue Native is a useful framework to build applications for mobile platforms using Vuejs. Vue Native compiles to React and uses components provided by React Native. As as the time of writing, some of its components require that you write JSX with the actual React Native components. Since Vue native works with React native, you can follow the official React native documentation to learn more about it.

You can view the source code for the demo on GitHub.

Creative Commons License