Front-End Web & Mobile

Amplify JavaScript releases support for Vue 3

Today, Amplify JavaScript adds support for version 3 of Vue JS to accompany current Vue support. The Amplify open-source client libraries provide use-case centric, opinionated, declarative, and easy-to-use interfaces across different categories of cloud powered operations enabling mobile and web developers to easily interact with their backends. These libraries are powered by the AWS cloud and offer a pluggable model which can be extended to use other providers. The libraries can be used with both new backends created using the Amplify CLI and existing backend resources. Our Amplify UI Components are an open-source UI toolkit that encapsulates cloud-connected workflows inside of cross-framework UI components.

In this tutorial, we’ll do the following:

  1. Create a new Vue 3 app as the base for this tutorial.
  2. Set up a base configuration for Amplify with Interactions category.
  3. Create a Chatbot component to add to your Vue 3 application

Prerequisites

Before you begin this tutorial, please visit the Amplify Documentation website and follow the prerequisites section. Once you complete the prerequisites, you will be ready to walk through the tutorial.

When you configure your AWS profile, please make sure your region supports AWS Lex. You can see the supported regions here.

Creating a new Vue app

First, we’ll create and start a new Vue app with @vue/cli, a CLI tool used to bootstrap a Vue app using current best practices. We’ll then add Amplify and initialize a new project. The following procedure will walk you through this process.

To create a new Vue app

From your projects directory, run the following commands:

npm install -g @vue/cli
vue create my-amplify-project 

? Please pick a preset: (Use arrow keys) 
❯ Default (Vue 3 Preview) ([Vue 3] babel, eslint) <--
Manually select features 

cd my-amplify-project

To run the app:

yarn serve

Press Ctrl + C to stop the server.

Initialize a new backend

Now that we have a running Vue app, it’s time to set up Amplify so that we can create the necessary backend services needed to support the app. From the root of the project, run:

amplify init

When you initialize Amplify you’ll be prompted for some information about the app:

? Enter a name for the project (myamplifyproject) 
? Enter a name for the environment dev
? Choose your default editor: Visual Studio Code
? Choose the type of app that you're building javascript
? What JavaScript framework are you using Vue
? Source Directory Path: src
? Distribution Directory Path: dist
? Build Command: npm run-script build
? Start Command: npm run-script serve
? Do you want to use an AWS profile? Yes
? Please choose the profile you want to use [Your AWS Profile]

Install Amplify libraries

The first step to using Amplify in the client is to install the necessary dependencies:

yarn add aws-amplify @aws-amplify/ui-components

Set up frontend

Next, we need to configure Amplify on the client so that we can use it to interact with our backend services.
Open src/main.js and add the following code below the last import:

import Amplify from 'aws-amplify';
import awsconfig from './aws-exports';
import {
  applyPolyfills,
  defineCustomElements, 
} from '@aws-amplify/ui-components/loader';

applyPolyfills().then(() => {
  defineCustomElements(window);
});
Amplify.configure(awsconfig);

Now Amplify and UI components have been successfully configured. As you add or remove categories and make updates to your backend configuration using the Amplify CLI, the configuration in aws-exports.js will update automatically.

Add Interactions Category

The next feature you will be adding to your Vue app is Interactions category, which uses Amazon Lex to host a conversational bot on AWS.

To add interactions to your Vue app

From your projects directory, run the following command, and answer the prompted questions as indicated.

$ amplify add interactions

? Provide a friendly resource name that will be used to label this category in the project: mychatbot
? Would you like to start with a sample chatbot or start from scratch? Start with a sample
? Choose a sample chatbot: BookTrip
? Please indicate if your use of this bot is subject to the Children's Online Privacy Protection Act (COPPA). No

Deploy the service by running the amplify push command.

amplify push

Add a chatbot to your Amplify Vue project

Now that we have added Interactions to the application, we will go ahead and add a chatbot component. In your src/App.vue update your code’s template:

<template>
  <amplify-chatbot
      bot-title="Chatbot Lex"
      bot-name="BookTrip_dev"
      welcome-message="Hello, how can I help you?"
      voice-enabled="true"
  />
</template>

To see the complete list of available props, please visit the documentation.

Run the application with yarn serve. You should see a chatbot rendered:

Lex Chatbot UI

You can interact with bot by sending a text message or clicking to the microphone button to talk.

Console warnings: If you see “failed to resolve component” warnings, you can create vue.config.js file in the app directory and use this gist to remove the warnings.

Listen to chat fulfillment

Now, let’s register a callback function that fires after a chat has been fulfilled. Chatbot fires a chatCompleted event whenever chat session has finishes. We can use Vue’s lifecycle hooks to listen to the event. Open src/App.vue and add the following code inside your script tag:

<script>
const handleChatComplete = (event) => {
    const { data, err } = event.detail;
    if (data) alert('success!\n' + JSON.stringify(data));
    if (err) alert(err);
};
export default {
    name: 'App',
    components: {},
    mounted() {
        this.$el.addEventListener('chatCompleted', handleChatComplete);
    },
    beforeUnmount() {
        this.$el.removeEventListener('chatCompleted', handleChatComplete);
    },
};
</script>

You can now see a pop up whenever you finish, or fail the chat. In practice, you would want to more with data. Here are some ideas:

  • Add result to a DynamoDB table using Amplify’s API category
  • Keep analytics of your orders with Amplify’s Analytics category
  • Render an image of the city that the user is traveling to.

Customization

Amplify provides two main technologies to customize the component to fit your application: CSS variables and slots.

Using CSS Variables to Style the Component

CSS variables are variables that contain specific css values reused throughout the component. You can assign them in your component stylesheet to style Amplify UI Components. Let’s change the text color background color of the text bubbles for example.

Open src/App.vue and add the following css variables:

<style>
:root {
  --amplify-primary-color: #fd8abd;
}

amplify-chatbot {
  --width: 450px;
  --height: 600px;
  --header-color: rgb(40, 40, 40);
  --bot-background-color: #eaebff;
  --bot-text-color: rgb(40, 40, 40);
  --user-background-color: #fd8abd;
}
</style>

Refresh the app and you should see the new colors applied to the component:

Pink styled chat bot

Feel free to use any color of your choice. To see the complete list of css variables that amplify-chatbot provides, please visit the documentation.

Using slots to Insert Custom Content

Slots are placeholders inside the component that can be filled with your own markup. For example, chatbot provides a header slot that you can replace. Let’s add a logo and a custom header. We’ll be using an amplify logo for this, but you can use any image and put it to src attribute instead. Update your template in src/App.vue:

<template>
    <amplify-chatbot
        bot-title="Chatbot Lex"
        bot-name="BookTrip_dev"
        welcome-message="Hello, how can I help you?"
        voice-enabled="{true}"
    >
        <!-- eslint-disable-next-line vue/no-deprecated-slot-attribute -->
        <div slot="header" className="custom-header">
            <img
                src="https://raw.githubusercontent.com/aws-amplify/amplify-js/main/vscode/images/logo.png"
                height="40"
            />
            Amplify Chatbot
        </div>
    </amplify-chatbot>
</template>

Note that we are adding a eslint disable line because it will suggest you to use v-slot instead. That is applicable for Vue component slot specification but not the web component slots that we use in this case.

Finally, let’s add some css style to improve our header. Append the following to your style in src/App.vue:

.custom-header {
  padding: 1.25rem 0.375rem 1.25rem 0.375rem;
  text-align: center;
  font-size: 1.6rem;
}

With that, refresh your app and you should see our customized chatbot component!

Final chat bot UI

Summary

In this blog post, we successfully created a Vue 3 web application with Amplify. We then configured Interactions category and rendered a conversational chatbot, which we customized with CSS Variables and slots.