Tips & Tricks

Get Started Building Apps With Vue.js in WebStorm

Vue Overview

Vue.js, the “Progressive JavaScript framework”, is user interface framework that you can use to build rich and responsive web apps. While Vue focuses on the UI (i.e., the view), it enables you to plug-in other libraries and tools to use for other scenarios, such as accessing back-end data or unit testing.

Before continuing, keep in mind that there are multiple ways to complete what you see in this post. After trying out Vue.js, you may prefer to add some small changes to the process that you see here.

Start a new Vue project

WebStorm relies on the Vue CLI to create projects, so it must be installed by running npm install --g @vue/cli in the terminal before trying to create one. The Vue CLI is the Vue Command Line Interface that helps to speed up development by scaffolding an application skeleton for you.

Open WebStorm and choose Create New Project on the IDE’s welcome screen. Select Vue.js from the list of project templates. Enter the location where the app will be generated, and the rest of the information as follows (also shown in the following image):

  • Node interpreter: Location of node.
  • vue-cli or @vue-cli: Location of CLI version you wish to use.

New Vue project

When you press Next, you can select the default preset (Babel and ESLint) or manually select other options. For this blog post, we’ll stick to the default.

Once the project has been created you see a folder structure similar to the following:

node_modules
public
src
└─assets
└─components

In the root, there are configuration files such as package.json and babel.config.js.

At this point, you have created a Vue project with WebStorm. To see the app in the browser, choose npm serve run/debug configuration in the navigation bar and click Run. You can then click on the local link (http://localhost:8080) under “App running at:” to launch a web browser and verify that it worked.

Running npm serve for the app

You’ll see the following page in the browser:

Check to see if app works after creation

Keep the browser open. You can switch back to it and it will automatically refresh showing the changes you make later.

The Vue instance

In order to manage web page activity, Vue needs an instance that serves as a wrapper around a root DOM element so it can track all activity for that element and its children. Tracking activity in this way makes Vue a reactive framework. Apps that are reactive in nature show changes to data in real time.

When you create a new Vue project, the CLI template adds code to the main.js file to make a new Vue instance, as shown here:

import Vue from 'vue';
new Vue({
  router: router,
  render: h => h(App)
}).$mount('#app');

The call to $mount('#app'); attaches the Vue instance to the root DOM element, which is an element with an id of “app”. You can find the root element inside of public\index.html.

Vue components

Vue is a framework for building modularized front-end apps, so it considers files with the .vue extension as components. Components behave like black boxes of functionality, but can communicate with each other through properties or state management. You can nest components or organize them alongside each other as siblings. Components contain three sections for code: template (HTML), script (JavaScript or TypeScript), and styles (CSS or any stylesheet language).

The project template creates a file called App.vue which is the primary component that is attached to the root element defined in the Vue instance.

The sample below from App.vue contains a template tag, and inside it is a div containing an image and a HelloWorld tag, which isn’t a standard HTML tag. It is, however, the name of a Vue component in the project. As you can see, when you create a Vue component, you can use it the same way that you would an HTML tag. Attributes in component tags are arguments that are passed into the component for processing. In this sample, the argument/attribute is the msg attribute.

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

The script section that is created by the CLI contains some basic code that imports the HelloWorld component and exports this component.

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {
    HelloWorld
  }
}
</script>

The style section contains standard CSS that styles fonts, colors, margins, and the like.

<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

Investigating the HelloWorld component reveals the same pattern – a template, script, and style section, exactly like in the App component. However, you’ll see some interesting and different syntax in the template:

<h1>{{ msg }}</h1>

In the previous code snippet, {{ msg }} is a string interpolation. String interpolations are a type of code construct that substitutes the double brackets and their contents with the result of a variable or simple expression. Examining the code in the script section of the HelloWorld.vue file reveals the msg variable as a property (called props) of the component. In the previous example, msg is an attribute of the HelloWorld tag, and that is how the message data is passed into the HelloWorld component.

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

Additionally, you can setup data, methods, and other parts of a component using the template, script, and styles sections.

Data binding and directives

As you have seen in the previous code sample, the {{ }} expression is the simplest way to data bind in Vue. However, binding with {{ }} only does one-way output binding.

Vue components also have the notion of a directive. A directive in Vue looks similar to an HTML attribute, but starts with a “v-”. Some common examples are v-bind, v-on, v-model, v-show, and v-pre. Here are some details about these common directives:

  • v-bind: Bind one or more attributes, or a prop to an expression.
  • v-on: Binds elements to events, such as the click, keyboard, or mouse event.
  • v-model: Helps update and sync data based on user input, providing two-way data binding.
  • v-show: Conditionally display an element.
  • v-pre: Display raw HTML.

The Vue directives documentation shows more directives as well as in-depth information on them.

Often, directives allow you to pass in arguments, such as the case for v-bind. For example, v-bind:href="url" means that this anchor tag is bound to the url data field or property that’s described in the component’s script section, and will display the value of that variable the same way the href attribute displays a link.

Let’s see binding in action by changing the welcome message to a welcome message with a link. First, modify props in HelloWorld so that you have a property called link that contains a string, like so:

props: {
  msg: String,
  link: String
}

Then modify the heading line in HelloWorld to look like the following:

<h1><a v-bind:href="link">{{ msg }}</a></h1>

As you can see, we are now using both styles of binding. The v-bind directive in the anchor tag now binds to the link prop while the msg remains the same. WebStorm features Vue directives prominently in the autocomplete list.

The final step is to modify the call to HelloWorld in the App component, so that the url is passed into HelloWorld:

<HelloWorld msg="Welcome to Your Vue.js App" link="http://vuejs.org"/>

vue-show-v-attributes

Switch to your browser or click on the link in the Run tool window to view the results. You should see the same message but it should now take you to http://vuejs.org.

Methods and events

If you want to respond to DOM events but not lose the reactivity that Vue provides, then you can bind to events in a similar fashion to how you bind to data. Vue provides directives for dealing with events, such as v-on. For example, to modify the HelloWorld.vue component so that it changes the welcome message, you’ll need to do a few things. First, comment or remove the msg from props and add that in as data instead. Do this by creating a function in the data property that returns a message named msg.

props: {
  //msg: String,
  link: String
},
data: function() {
  return { msg: "Welcome to Your Vue.js App" };
}

The next step is to add code to the component that responds to a click event and displays a new message. Notice that you reference msg with the this keyword. The entire script segment should look like the following:

export default {
  name: 'HelloWorld',
  props: {
    //msg: String,
    link: String
  },
  data: function() {
    return {msg: "Welcome to Your Vue.js App"};
  },
  methods: {
    changeMessage: function() {
      this.msg = "Vue.js is awesome!";
    }
  }
}

In the template section of HelloWorld, use the v-on directive to so that the changeMessage method is called when the button is clicked.

<button v-on:click="changeMessage">Change Message</button>

In the App.vue file, remove the HelloWorld’s msg attribute since it’s no longer needed.

<HelloWorld link="http://vuejs.org"></HelloWorld>

Return to the browser and verify that the button changes the contents of the message when it’s clicked.

vue-browser-final-launched

More Vue features and the Vue ecosystem

One blog post couldn’t possibly cover everything Vue has to offer. The Vue guide can help you find more advanced features than are covered here.

If you want to investigate more things that you can do with Vue, check out the frameworks and utilities that make up its ecosystem:

  • Vuetify.js: A framework for Vue apps that helps to build beautiful apps with styles and UI components.
  • VueX: A state management library for Vue.js apps.
  • Vue-resource, Axios, and Fetch: Libraries for making web service requests and managing the HTTP request object.
  • Vue-router: A utility for creating SPA style apps with Vue components.

Summary

This blog post has shown that you can get up to speed with Vue.js quickly using WebStorm. Keep an eye out for more Vue.js content on how to build components, using frameworks from the Vue ecosystem, and other advanced Vue topics.

image description