NativeScript and Vue.js: Toast Plugin

NativeScript and Vue.js: Toast Plugin

Continuing the NativeScript and Vue series, let's create an application that takes advantage of the nativescript-toast plugin. We'll start off by creating a new NativeScript Vue application:

# Install the NativeScript CLI
npm install nativescript -g

# New NativeScript Vue project
tns create NSVueToast --template nativescript-vue-template

# Change directory
cd NSVueToast

# Run on iOS
tns run ios

We can then add the NativeScript plugin:

# Add the NativeScript Toast plugin
tns plugin add nativescript-toast

I'll then replace everything in app.js with the following:

const Vue = require('nativescript-vue');

// Import the NativeScript Toast plugin
const Toast = require('nativescript-toast');

new Vue({
	template: `
    <page>
      <action-bar title="NativeScript Toast"></action-bar>
      <stack-layout>
        <text-field v-model="message"></text-field>
        <button @tap="showToast()" text="Show Toast"></button>
      </stack-layout>
    </page>
    `
}).$start();

We're importing Toast from nativescript-toast and this allows us to use it inside of our Vue instance. We also have a simple template - one with a text field and a button - the button is tapped I want our toast to appear.

new Vue({
  data: {
    message: 'Hello NativeScript Vue'
  },
  methods: {
    showToast() {
      const myToaast = Toast.makeText(this.message, 'long');

      myToast.show();
    }
  },
  ...

Awesome! Our text field is now prepopulated with a message and our showToast() method will show the text of that message with .a 'long' duration. If you're confused why this.message is referring to the message string within our data object, it's because Vue proxies everything to be referrenced in such a way.

About Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Comments