NativeScript and Vue.js: 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 myToast = 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.