Vue Works App

Posted on  by admin
I’ve danced the JavaScript framework shuffle for years starting with jQuery, then on to Angular. After being frustrated with Angular’s complexity, I found React and thought I was in the clear.

Then I found Vue.js. It just felt right. It worked as expected. The documentation was incredible. Templating was eloquent. There was a unanimous consensus around how to handle state management, conditional rendering, two-way binding, routing, and more.

This tutorial will take you step by step through scaffolding a Vue.js project, offloading secure authentication to Okta’s OpenID Connect API (OIDC), locking down protected routes, and performing CRUD operations through a backend REST API server.

This tutorial uses the following technologies but doesn’t require intimate knowledge to follow along:.

Vue.js with Vue CLI, vue-router, and the Okta Vue SDK.

  • Node with Express, Okta JWT Verifier, Sequelize, and Finale.
  • Table of Contents. Add a Backend REST API Server.
  • Complete the Posts Manager Component.
  • Vue.js is a robust but simple JavaScript framework.
  • It has one of the lowest barriers to entry of any modern framework while providing all the required features for high performance web applications.
  • This tutorial covers two primary builds, a frontend web app and backend REST API server.
  • The frontend will be a single page application (SPA) with a homepage, login and logout, and a posts manager.
  • Okta’s OpenID Connect (OIDC) will handle our web app’s authentication through the use of Okta’s Vue SDK.
  • If an unauthenticated user navigates to the posts manager, the web app should attempt to authenticate the user.

The server will run Express with Sequelize and Finale.

At a high level, with Sequelize and Finale you can quickly generate dynamic REST endpoints with just a few lines of code.

  • You will use JWT-based authentication when making requests from the web app and Okta’s JWT Verifier in an Express middleware to validate the token.
  • Your app will expose the following endpoints which all require requests to have a valid access token.
  • To get your project off the ground quickly you can leverage the scaffolding functionality from Vue CLI.
  • For this tutorial, you are going to use the progressive web app (PWA) template that includes a handful of features including webpack, hot reloading, CSS extraction, and unit testing.
  • If you’re not familiar with the tenets of PWA, check out our ultimate guide to progressive web applications.

Complete the Posts Manager Component

To install the Vue CLI run:. Next, you need to initialize your project. When you run the vue init command just accept all the default values.

Point your favorite browser to http://localhost:8080 and you should see the fruits of your labor:.

Extra Credit: Check out the other templates available for the Vue CLI.

Let’s install bootstrap-vue so you can take advantage of the various premade components (plus you can keep the focus on functionality and not on custom CSS):.

To complete the installation, modify ./src/main.js to include bootstrap-vue and import the required CSS files.

  • Your ./src/main.js file should look like this:. Dealing with authentication in a web app is the bane of every developer’s existence.
  • That’s where Okta comes in to secure your web applications with minimal code. Before you begin, you’ll need a free Okta developer account.
  • Install the Okta CLI and run okta register to sign up for a new account.
  • If you already have an account, run okta login.Then, run okta apps create.

Select the default app name, or change it as you see fit.Choose Single-Page App and press Enter.

  1. Use http://localhost:8080/callback for the Redirect URI and accept the default Logout Redirect URI of http://localhost:8080. The Okta CLI will create an OIDC Single-Page App in your Okta Org.
  2. It will add the redirect URIs you specified and grant access to the Everyone group.
  3. It will also add a trusted origin for http://localhost:8080. You will see output like the following when it’s finished:.
  4. NOTE: You can also use the Okta Admin Console to create your app.
  5. See Create a Vue App for more information. Then, install the Okta Vue SDK and its peer dependency, the Okta AuthJS SDK:. Open ./src/router/index.js and replace the entire file with the following code.

You’ll need to replace {yourOktaDomain} and {clientId} with the values from the app you just created.

Building our movie app

This will inject an authClient object into your Vue instance which can be accessed by calling this.$auth anywhere inside your Vue instance.

The final step of Okta’s authentication flow is redirecting the user back to your app with the token values in the URL. The LoginCallback component included in the SDK handles the redirect and persists the tokens on the browser.

You also need to lock down protected routes from being accessed by unauthenticated users. This is accomplished by implementing a navigation guard. As the name suggests, navigation guards are primarily used to guard navigations either by redirecting or canceling. The Okta Vue SDK comes with navigation guards built-in, so any route that has the following metadata will be protected.

  • The web app’s layout is located in a component ./src/App.vue.
  • You can use the router-view component to render the matched component for the given path.
  • For the main menu, you’ll want to change the visibility of certain menu items based on the status of the activeUser:.
  • Not Authenticated: Show only Login. Authenticated: Show only Logout.
  • You can toggle the visibility of these menu items using the v-if directive in Vue.js that checks the existence of activeUser on the component.
  • When the component is loaded (which calls created()) or when a route changes we want to refresh the activeUser. Open ./src/App.vue and copy/paste the following code. Every login must have a logout. The following snippet will log out your user and then redirect the user to the homepage.
  • This method is called when a user clicks on the logout link in the nav. Components are the building blocks within Vue.js.

Each of your pages will be defined in the app as a component.

Customize Your App Layout in Vue

Conclusion

Since the Vue CLI webpack template utilizes vue-loader, your component source files have a convention that separates template, script, and style (see here). Now that you’ve added vue-bootstrap, modify ./src/components/Hello.vue to remove the boilerplate links vue-cli generates.

At this point you can stub out the Post Manager page to test your authentication flow.

  • Once you confirm authentication works, you’ll start to build out the API calls and components required to perform CRUD operations on your Posts model.
  • Create a new file ./src/components/PostsManager.vue and paste the following code:.
  • In your terminal run npm run dev (if it’s not already running). Navigate to http://localhost:8080 and you should see the new homepage. If you click Posts Manager or Login you should be directed to Okta’s flow. Enter your Okta developer account credentials. NOTE: If you are logged in to your Okta Developer Account you will be redirected automatically back to the app.

You can test this by using incognito or private browsing mode. If successful, you should return to the homepage logged in.

Clicking on Posts Manager link should render the protected component.

Introduction to Vue.js Axios

Now that users can securely authenticate, you can build the REST API server to perform CRUD operations on a post model. Add the following dependencies to your project:.

Then, create the file ./src/server.js and paste the following code. Make sure to replace the variables {yourOktaDomain} and {clientId} in the above code with values from your OIDC app in Okta.

Step 3 — Creating a Header Component

Sequelize is a promise-based ORM for Node.js. It supports the dialects PostgreSQL, MySQL, SQLite, and MSSQL and features solid transaction support, relations, read replication, and more. For ease of this tutorial, you’re going to use SQLite to limit external dependencies.

The following code initializes a Sequelize instance using SQLite as your driver. Each post has a title and body. (The fields createdAt, and updatedAt are added by Sequelize automatically). With Sequelize, you define models by calling define() on your instance.

Finale creates flexible REST endpoints from Sequelize models within an Express app. If you ever coded REST endpoints you know how much repetition there is.

This is the most crucial component of your REST API server. Without this middleware any user can perform CRUD operations on our database.

If no authorization header is present, or the access token is invalid, or the audience doesn’t match, the API call will fail and return an error.

Open a new terminal window and run the server with the command node ./src/server. You should see debug information from Sequelize and the app listening on port 8081. Now that the REST API server is complete, you can start wiring up your posts manager to fetch posts, create posts, edit posts, and delete posts.

I always centralize my API integrations into a single helper module.

Test Your Vue.js + Node CRUD App

This keeps the code in components much cleaner and provides single location in case you need to change anything with the API request.

Add Authentication with Okta

Create a file ./src/api.js and copy/paste the following code into it:. When you authenticate with OIDC, an access token is persisted locally in the browser.

Since each API request must have an access token, you can fetch it from the authentication client and set it in the request. By creating the following proxy methods inside your API helper, the code outside the helper module remains clean and semantic.

You now have all the components required to wire up your posts manager component to make CRUD operations via the REST API. Open ./src/components/PostsManager.vue and copy/paste the following code.

You’ll use api.getPosts() to fetch posts from your REST API server. You should refresh the list of posts when the component is loaded and after any mutating operation (create, update, or delete).

The attribute this.loading is toggled so the UI can reflect the pending API call. You might not see the loading message since the API request is not going out to the internet.

A form is included in the component to save a post. It’s wired up to call savePosts() when the form is submitted and its inputs are bound to the model object on the component.

When savePost() is called, it will perform either an update or create based on the existence of model.id.

This is mostly a shortcut to not have to define two separate forms for creating and updating. When updating a post, you first must load the post into the form. This sets model.id which will the trigger an update in savePost().

Important: The Object.assign() call copies the value of the post argument rather than the reference.

When dealing with mutation of objects in Vue, you should always set to the value, not reference.

To delete a post simply call api.deletePost(id). It’s always good to confirm before delete so let’s throw in a native confirmation alert box to make sure the click was intentional.

Create Your Vue.js App

Add Finale

Make sure both the server and frontend are running. Navigate to http://localhost:8080 and give it a whirl. As I said at the top of this post, I think Vue stands head and shoulders above other frameworks.

Here are five quick reasons why:. HTML-based templating and native two-way binding. Widely agreed upon ways to handle routing, state management, webpack configuration, and isomorphic web apps. Massive community supported resources, components, libraries, and projects.

Vue feels very similar to React (without the JSX!) which lowers the barrier to entry for those with React experience.

Moving between React and Vue isn’t very difficult. I covered a lot of material in this tutorial but don’t feel bad if you didn’t grasp everything the first time.

The more you work with these technologies, the more familiar they will become. To learn more about Vue.js head over to https://vuejs.org or check out these other great resources from the @oktadev team:.

You can find the source code for the application developed in this post at https://github.com/oktadeveloper/okta-vue-node-example.

Hit me up in the comments with any questions, and as always, follow @oktadev on Twitter to see all the cool content our dev team is creating.

  • Apr 12, 2021: Upgraded to use Okta Vue 3.1.0 and Okta JWT Verifier 2.1.0.
  • You can see the changes to the example in okta-vue-node-example#3 or view the changes in this blog post.
  • Sep 6, 2019: Updated to migrate from Epilogue to Finale. Epilogue is no longer maintained. Thanks to Chris Roberts for the tip! See the code changes in okta-vue-node-example#3. Changes to this article can be viewed in okta.github.io#3040.

Install Bootstrap

Apr 16, 2018: Updated to use the latest dependencies, including Okta’s Vue SDK 1.0.0. See the code changes in okta-vue-node-example#2. Changes to this article can be viewed in okta.github.io#1959.

Mar 12, 2018: Updated to use the latest dependencies, including Bootstrap 4.0.0.

  • See the code changes in okta-vue-node-example#1.
  • Changes to this article can be viewed in okta.github.io#1837. Okta Developer Blog Comment Policy.

We welcome relevant and respectful comments. Off-topic comments may be removed.

The Node.js provides a Vue.js data() method to the user. Basically in vue.js data() we defined collection of logic and stored in component using vue.js we can access data Node.jsassociated with a vue instance.

Components are reusable as many times as per requirement. But each time it uses a separate component and also creates a new instance. When we use a data function at that time each instance maintains a separate copy of the return data object.

Building the app

Most of vue.js uses API to fetch and post data. It is safe because it does not affect the changes outside the scope. Explanation: The above syntax component is reusable with instance name and notice that when we use data does not provide objects directly.

Instead a component data option is function so each instance is maintaining a separate copy of return data by using the following syntax.

We must install Node.js 10.x and above on your system and you can verify by using node –v command in your terminal.

We must install the latest version of Vue on your system. We must install the Vue CLI 3.0 version on your system.

We required basic knowledge about Node.js. We required basic knowledge about Vue.js and components.

About Vue.js

Let’s see how we can implement Vue.js data() with different examples as follows. Basic example of data method. Node JS Training Program (3 Courses, 7 Projects)3 Online Courses | 7 Hands-on Projects | 25+ Hours | Verifiable Certificate of Completion | Lifetime Access 4.5 (8,311 ratings).

Take Your Vue.js Frontend and Auth Flows for a Test Drive

Related Courses. Vue JS Training (1 Courses, 3 Project)JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes).

In this example, we only made changes in the App.vue file in which we added a data method to access the title.

Illustrate the end result of the above declaration by using the use of the following snapshot.

  1. For Data with Method. Explanation: In the above example first we created a data function that returns an object.
  2. Every property of vue is added to the vue reactivity system so that if we make some changes in the program that is updated.
  3. So that we add title property in our template by using {{}} double curly braces.
  4. Vue js must require {{}} double curly to pass javaScript Expression.

Step 1 — Downloading Vue CLI 3

In the second part of the program we have created a method and the method also has an object. Here we create a Msgmethod which returns a string. Inside the method, we access data object property by using this and finally we added in the template tag. Illustrate the end result of the above declaration by using the use of the following snapshot.

Explanation: This is another simple example of data function with methods. Illustrate the end result of the above declaration by using the use of the following snapshot.

Emit data in vue.js with event. Explanation: In the above component, we sent messages from the child component to the parent component.

In the above template, we use a button to send the message to the parent component.

See in this template we use the changes function whenever we submit a message to the parent component. Then we added the following code in the App.vue file.

Explanation: In this file actually we are listing our event. In the first component, we just send messages from the child component to the parent component but in this we actually manipulate them.

In this file, we import the HelloWorld.vue component for listening to custom events by using changeMsg function.

Step 4 — Creating the Footer Component

We also define a setMessage function to handle custom events. The remaining part is the css part this necessary for design purpose.

In this example we by default content of vue. Illustrate the end result of the above declaration by using the use of the following snapshot.

Before Click on Button:. After Submit Message:.

We hope from this article you have understood about the vue.js data. From the above article, we have learned the basic syntax of the vue.js data function. We have also learned how we can implement them in Node.js with examples. From this article, we have learned how we can handle vue.js data as well as components in Node.js.

This is a guide to Vue.js data() Here we also discuss the definition and how data() works in vue.js along with different examples and its code implementation.

You may also have a look at the following articles to learn more –.

  1. JavaScript is regarded as one of the most commonly used programming languages in the world, as it doesn’t just excel at manipulating elements on the frontend; with this same language, you can create cross-platform mobile applications, develop APIs and work with backend infrastructure, and create desktop applications.
  2. While there have been numerous libraries and frameworks for all of these aspects, Electron stands out when it comes to developing desktop apps with JavaScript, and in this post, we’ll look at how to use Vue with Electron to create our first cross-platform desktop application.
  3. This article assumes the following prerequisites:. Basic understanding of JavaScript. Basic familiarity with Vue. Node.js and npm installed.
  4. Prior experience with Electron is a plus, but not required. Electron is an open source JavaScript framework for building native cross-platform desktop applications with web technologies (HTML, CSS, and JavaScript).
  5. This implies that if you have prior familiarity working with these technologies, you can use the same codebase to develop a desktop application for Windows, Linux, and macOS.

Behind the scenes, Electron combines the Chromium engine with Node.js runtime to read and run your codebase as a standalone desktop program.

And, to prove its capabilities, popular desktop programs created using Electron include Slack, VS Code, and WhatsApp Desktop.

The following are some of the advantages of using Electron:.

Do More With Vue!

Single codebase — With Electron, you’ll only need a single codebase to create desktop applications for different operating systems.

Leverage web skills — If you have prior experience working with basic web stacks (HTML, CSS, and Javascript), it is super easy to get started with Electron. Big community — The Electron community is quite a big and active one, a major factor adding to this is because the framework is being used and supported by top companies.

Just like anything else, there are some downsides to building desktop applications with Electron too. Some of them include:. Higher resource consumption — Desktop applications written in Electron are known to consume more CPU and RAM compared to apps written in other environments, such as Java FX, Objective C, and so on.

Larger app size — As previously stated, Electron applications bundle the Chromium engine during the build process, which results in a big app size even for a simple application.

Add a Backend REST API Server

If you’ve worked with Vue before, it’s fairly simple to get started with Electron. This is possible with a Vue CLI plugin called Electron Builder, and in the coming sections, we’ll learn how this plugin works by building a sample application that returns a wholesome list of trending movies from themoviedb API.

Here is a preview of what our movie application will look like:. Since Electron builder is a Vue CLI plugin. This means we’ll need to install the Vue CLI itself before we can work with it.

To do this run:. Running the above command will install the most recent stable version of Vue CLI, and you can verify that it was successful by running vue -V, which should print out the installed version of Vue.

Introduction to Vue.js data()

Next, we want to create a new Vue application, so go ahead and run the command below to create a new app named vue-desktop:. The final step is to add the Vue Electron Builder plugin, and we can do this by running the command below:.

What is Electron?

This will ask you for the version of Electron you want to add to this Vue project, and once you’ve done so, you should see a success message indicating that Electron Builder was installed. You can then launch the app by running:.

And you should see an output similar to the screenshot below:.

  • Closing the dev tool, you should see the complete preview of the application, like in the image below:.
  • When you open the project folder in your preferred text editor, you should be presented with the following files and directory as shown in the image below.
  • And if you’ve worked with Vue CLI in the past, you will notice that the file structure is pretty much the same.

The only change is the addition of a new background.js file, and this file is responsible for running our Vue application as a stand-alone desktop application.

In this file, you can configure the default width and height of the window the application launches with, set the application title, add an auto-update feature, among other things.

Now that we’re up to speed with Vue Electron Builder, let’s go ahead and start building our trending movie application. The first step is to open up public/index.html and add an entry for Bootstrap and Font Awesome in the head section, like in the code below:.

Next, in the src/components folder, create a new file called MovieCard.vue and paste the following code into it:.

Here, we have created a MovieCard component that accepts a prop containing all of the details for each movie.

The next step is to delete all of the code contained in src/App.vue and update with the following:.

At this point, if we run our application, we should have the following output:. The final step is to define a method that fetches the most popular movies from the TMDB API.

This process would require you to create a free account with them to retrieve your API key.

To do this, update src/App.vue with the following code:. Here, we imported the MovieCard component we created earlier in the script section, and we also added a new method, getTrendingMovies(), which is responsible for loading our movies from TMDB API, and we then ran this function in the mounted hook.

And a small change to our markup is looping all of the results returned from TMDB into our MovieCard component.

If we refresh our application at this stage, everything should work fine, and you should have an output similar to the image below:.

Step 2 — Generating a Single-Page Application

The Electron icon is set as the default icon for your app, and most of the time, you’ll probably want to set your custom icon. You can simply update the app icon by adding a new icon entry in the newBrowserWindow() method present in background.js like below:.

Compiling our application as a stand-alone executable file is straightforward.

  1. We can do so by running the command below:. Keep in mind the executable app that is generated is dependent on the operating system you’re working with.
  2. However, Electron Builder allows you to define which platform (or platforms) you want to generate executables for.
  3. Available options include Mac, Win, and Linux. This means to build the Linux version of your applications, you’ll run the following command:.
  4. Throughout this tutorial, we’ve looked at how to use Electron and Vue to create a cross-platform desktop application. We also built an example trending movies application to understand how things worked.

Experience your Vue apps exactly how a user does

And the code for the complete application can be found here on GitHub. If you enjoy reading the article, do leave a comment below!

Vue.js Axios is defined as an HTTP client request for the node and the browser.

  1. Axios can be done with simple JavaScript or React and Vue.
  2. Axios is an Excellent HTTP library that executes on both client and a server, which makes an API request, does the task to produce the result and specifies easier concepts to read and debug.

Vue.js is the front-end JavaScript Framework to build tools and libraries.

The Axios works well in the platform like node.js and browsers.

  1. Vue.js Axios is a leading framework to Consume REST APIs is easy with them. Here all the example code is executed in Visual Studio Code with Node.js.
  2. The Structure is given as :. Using Simple GET request. Vue lacks a built-in HTTP library, so Axios library is recommended to keep interaction with REST API.
  3. So here in this article, we have used JSON PLACEHOLDER API to take a few sample data for the application.

Generally, Axios makes HTTP requests like GET, POST, PUT, DELETE.

Vue + Electron

The methods includes axios.get() and axios.post(). Axios has good benefits like supports older versions of browsers, JSON package transformations, and supports the upload process.

The Following working Steps to be followed:.

  1. 1.Installation- Axios. 2.Creating Vue.js App to start vue CLI app. To install vue-Axios (HTTP Client), the following command is used:.
  2. Node JS Training Program (3 Courses, 7 Projects)3 Online Courses | 7 Hands-on Projects | 25+ Hours | Verifiable Certificate of Completion | Lifetime Access 4.5 (8,319 ratings).
  3. Related Courses. Vue JS Training (1 Courses, 3 Project)JavaScript Training Program (39 Courses, 23 Projects, 4 Quizzes).
  4. The following sample code is reflected in main.js. To run a Vue app. This directs to http://localhost:8080. Installing Vue Dependencies.
  5. The next step is to create Components; it is done like src -> Components and adds the code inside the component files.

Finally, the sample demonstration is given in Example 1.

To start an application, HTML declaration is done, which acts as a front-end UI.

Secondly, to perform Vue.js Component. Lastly, add API to the vue.js Component.

To handle errors in the Axios library ‘catch’ method is preferred as we use this in case of any network failure while requesting data.

Using the Loading indicator while the page takes too much time to the respond from the backend.

Examples of Vue.js data()

In this section, we shall see how to use Vue.js and Axios together. Showing Simple Request Page. Next, this Java Script part shows application Logic. We have used mount () to the API to make a request, and the results are saved. Creating Basic Vue Application by building an HTML Page by creating html in editor.

Fetching data from API’s through Vue.js Axios. Explanation: To do this, we have already created a project in Vue using Vue-CLI, and next is by installing the Axios library as shown in the above Screenshot.

So this example fetches data from the JSON API, which is created already, and we get that request by .get () in the code.

And now the output looks like this when you open a browser.

  1. Fetching data from the third party.
  2. Code: index.html. By now, we have understood the functionality of the application and the fundamentals.
  3. This article would be a pretty starting point to handle API calls in any application and helpful in future projects.
  4. Therefore, we have achieved here how to send an HTTP request to the Node.js and fetches respective data from the database.

This is a guide to Vue.js Axios. Here we discuss How Axios works in Vue.js and Examples along with the codes and outputs.

  1. You may also have a look at the following articles to learn more –. The author selected Open Sourcing Mental Illness to receive a donation as part of the Write for DOnations program.
  2. Vue.js is a popular JavaScript framework for creating user interfaces. Created in 2014 by Evan You (formally of Google), Vue.js is often described as a combination of React and Angular, borrowing the prop-driven development of React and the templating power of Angular.
  3. This makes Vue an accessible framework for beginners to pick up, especially since it focuses on traditional HTML and CSS, rather than being a CSS-in-JS framework like React or relying on TypeScript (a superset of JavaScript) like Angular does.

When starting a new project, it’s best to familiarize yourself with the technology’s tools and features.

One important tool for Vue.js development is its command line interface (CLI) known as Vue CLI 3.

The Vue CLI offers a number of useful features that enhance the Vue development experience, but the main feature is its ability to generate and pre-configure a new single-page application with the vue create command.

By the end of this tutorial, you will have a working Vue.js application running on a local Node server.

Updating Posts

This local server uses hot module reloading via Webpack to provide immediate feedback, rendered in-browser as you work. Along the way, you will create .vue single-file components (SFC), such as a header and a footer. All of this you can save as a solid foundation for any future Vue projects. To follow this tutorial, you will need the following:.

Node.js version 10.6.0 or greater installed on your computer. To install this on macOS or Ubuntu 18.04, follow the steps in How To Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04. You will also need a basic knowledge of JavaScript, HTML, and CSS, which you can find in our How To Build a Website With HTML series, How To Build a Website With CSS series, and in How To Code in JavaScript.

To download Vue CLI 3, you will need to run a command either via npm or Yarn, whichever you prefer.

Cons

npm or Node Package Manager is a way to download and manage other people’s code to use in your project as a dependency. Yarn, on the other hand, executes NPM commands under the hood but provides additional features like caching.