Vue.js Tutorial: Getting Started & 10 Best Practices

Share this article

Vue.js Tutorial: Getting Started & 10 Best Practices

Vue.js (also known as Vue) is a popular JavaScript framework for building user interfaces. Its core library focuses on the view layer only, making it easy to integrate with other libraries or existing projects. In this tutorial, we’ll cover the basics of Vue and guide you through the process of creating a simple app.

Key Takeaways

  • Vue.js is a popular JavaScript framework that focuses on the view layer, making it easy to integrate with other libraries or existing projects. You can create a new Vue project using Node.js and the Vue CLI, which will provide a structured template for your application.
  • Components are the building blocks of a Vue app and can be used to create complex user interfaces. Vue also provides directives for adding interactivity to your components, conditional rendering, and looping through arrays. Best practices include breaking down your application into small, reusable components and using computed properties for calculations that depend on reactive data.
  • Avoid common pitfalls in Vue such as overusing v-if and v-for on the same element, directly modifying props within a child component, and overusing global mixins. Always use the key attribute with v-for to help Vue track the identity of each node. When building your application for production, ensure you optimize for better performance.

Setting Up Your Environment

To get started with Vue, you’ll need to have Node.js installed on your computer. You can download it from the official website. Once you have Node.js installed, you can use the Node Package Manager (npm) to install Vue.

Open your terminal or command prompt and run the following command:

npm install -g vue

This will install the latest version of Vue globally on your system.

Creating a New Vue Project

Now that you have Vue installed, let’s create a new project. We’ll use the Vue CLI to generate a new project template. First, install the Vue CLI by running:

npm install -g @vue/cli

Next, create a new project by running:

vue create my-vue-app

Replace my-vue-app with the name you want for your project. The CLI will prompt you to choose a preset. Select the default preset to keep things simple for this tutorial.

Once the project is created, navigate to the project folder:

cd my-vue-app

Now, start the development server by running:

npm run serve

This will launch a local server at http://localhost:8080/. Open this URL in your browser to see your new Vue app.

Understanding the Vue Project Structure

Let’s take a moment to understand the structure of the generated project. The main folders and files you’ll work with are:

  • public: contains the static assets and the index.html file.
  • src: contains the source code for your app, including components, assets, and the main App.vue file.
  • src/main.js: the entry point for your app. This is where Vue is imported and the root Vue instance is created.
  • src/App.vue: the main app component. This is where you’ll build your app’s layout and structure.

Creating Your First Vue Component

Components are the building blocks of a Vue app. They are reusable pieces of code that can be combined to create complex user interfaces. Let’s create a simple component to display a message.

In the src/components folder, create a new file called Message.vue. Add the following code:

<template>
<div>
<p>{{ message }}</p>
</div>
</template>

<script>
export default {
data() {
return {
message: 'Hello, Vue!'
};
}
};
</script>

This component has a single data property called message. The template displays the value of this property inside a paragraph element.

Now, let’s use this component in our main App.vue file. First, import the Message component at the top of the script section:

import Message from './components/Message.vue';

Next, register the component by adding it to the components object:

components: {
Message
}

Finally, add the Message component to the template:

<Message />

Your App.vue file should now look like this:

<template>
<div id="app">
<Message />
</div>
</template>

<script>
import Message from './components/Message.vue';

export default {
name: 'App',
components: {
Message
}
};
</script>

Save your changes and check your browser. You should see the “Hello, Vue!” message displayed on the page.

Adding Interactivity with Vue Directives

Vue provides a set of directives that allow you to add interactivity to your components. Let’s create a simple counter app to demonstrate how to use directives.

Update the Message.vue component with the following code:

<div>
<p>{{ message }}</p>
<p>Counter: {{ counter }}</p>
<button @click="increment">Increment</button>
</div>

<script>
export default {
data() {
return {
message: 'Hello, Vue!',
counter: 0
};
},
methods: {
increment() {
this.counter++;
}
}
};
</script>

We’ve added a new data property called counter and a method called increment. The increment method increases the value of counter by 1. In the template, we’ve added a paragraph to display the counter value and a button to trigger the increment method.

The @click directive is used to attach the increment method to the button’s click event. When the button is clicked, the increment method will be called, and the counter value will increase.

Save your changes and check your browser. You should see the counter app working as expected.

Using Conditional Rendering and Loops

Vue provides directives for conditional rendering and looping through arrays. Let’s update our Message.vue component to demonstrate these features.

Add the following code to the Message.vue component:

<div>
<p>{{ message }}</p>
<p>Counter: {{ counter }}</p>
<button @click="increment">Increment</button>
<p v-if="counter >= 5">You've reached 5 or more!</p>
<ul>
<li v-for="number in numbers" :key="number">{{ number }}</li>
</ul>
</div>

<script>
export default {
data() {
return {
message: 'Hello, Vue!',
counter: 0,
numbers: [1, 2, 3, 4, 5]
};
},
methods: {
increment() {
this.counter++;
}

We’ve added a new data property called numbers, which is an array of integers. We’ve also added a paragraph that will only be displayed if the counter value is 5 or greater, using the v-if directive.

The v-for directive is used to loop through the numbers array and create a list item for each number. The :key attribute is used to provide a unique key for each list item, which is required for performance reasons.

Save your changes and check your browser. You should see the new features working as expected.

Vue Best Practices

  1. Component-based architecture. Break down your application into small, reusable components. This promotes maintainability, readability, and testability.

  2. Single-file components. Use .vue files to encapsulate the template, script, and styles for each component. This keeps your code organized and easy to understand.

  3. Naming conventions. Adopt a consistent naming convention for components, such as PascalCase or kebab-case. This makes it easier to identify and reference components in your project.

  4. Props validation. Define and validate props for components to ensure correct data types and values are passed. This helps catch errors early and improves code readability.

  5. Computed properties. Use computed properties instead of methods for calculations that depend on reactive data. Computed properties are cached and only re-evaluated when their dependencies change, improving performance.

  6. Watchers. Use watchers sparingly and only when necessary. Prefer computed properties or methods for reacting to data changes.

  7. Event handling. Use Vue’s built-in event handling system (v-on or @) instead of directly manipulating the DOM. This ensures your code is more maintainable and less prone to errors.

  8. Scoped CSS. Scope your component styles using the scoped attribute in the style tag. This prevents styles from leaking to other components and ensures proper encapsulation.

  9. Vuex for state management. Use Vuex to manage your application’s state when dealing with complex data flows or shared state between components. This centralizes state management and makes your code more predictable and maintainable.

  10. Testing. Write unit tests for your components and end-to-end tests for your application. This ensures the stability of your code and helps catch errors early.

Avoiding Vue’s Common Pitfalls

  1. Overusing v-if and v-for. Avoid using v-if and v-for on the same element, as it can lead to performance issues. Instead, use computed properties to filter the list before rendering.

  2. Directly modifying props. Never modify a prop directly within a child component. Instead, emit an event to the parent component to update the prop.

  3. Not using key attribute with v-for. Always use the key attribute with v-for to help Vue track the identity of each node. This improves performance and prevents unexpected behavior.

  4. Overusing global mixins. Use global mixins sparingly, as they can introduce unintended side effects and make your code harder to understand. Prefer local mixins or utility functions.

  5. Overusing $refs. Avoid using $refs to manipulate child components directly. Instead, use props and events to communicate between components.

  6. Not optimizing for production. Ensure you build your application for production using Vue’s build tools. This minimizes the bundle size and optimizes the application for better performance.

  7. Ignoring accessibility. Pay attention to accessibility best practices, such as using semantic HTML, ARIA attributes, and keyboard navigation. This ensures your application is usable by a wider audience.

Conclusion

In this tutorial, we’ve covered the basics of Vue, including setting up your environment, creating a new project, working with components, and using directives for interactivity, conditional rendering, and loops. With this foundation, you can continue to explore the powerful features of Vue and build more complex applications.

Remember to consult the official Vue documentation for more in-depth information and examples. Happy coding!

For insights into how Vue.js is implemented across various frameworks for web apps, look into Vue.js boilerplates.

Frequently Asked Questions (FAQs) about Vue.js Setup

What are the prerequisites for setting up Vue.js?

Before setting up Vue.js, you need to have a basic understanding of HTML, CSS, and JavaScript. You should also be familiar with ES6 syntax, which includes let and const statements, arrow functions, classes, modules, promises, and destructuring assignments. Additionally, you need to have Node.js and npm installed on your computer. Node.js is a JavaScript runtime that’s used to run JavaScript on a server, while npm is a package manager for Node.js.

How do I install Vue.js?

Vue.js can be installed in two ways: by using a script tag or by using the Vue CLI. The script tag method is the easiest and involves adding a script tag to your HTML file that points to the Vue.js library. The Vue CLI method is more complex but offers more flexibility. It involves installing the Vue CLI globally on your computer using npm, then using the Vue CLI to create a new Vue project.

What is Vue CLI and why is it important?

Vue CLI is a command-line interface for Vue.js that helps you scaffold and manage Vue.js projects. It provides a full system for rapid Vue.js development, including project scaffolding, a development server with hot module replacement, and a build system for production. Using Vue CLI can greatly speed up your Vue.js development process.

How do I create a new Vue project using Vue CLI?

To create a new Vue project using Vue CLI, first open a terminal or command prompt. Then navigate to the directory where you want to create your project and run the command “vue create project-name”, replacing “project-name” with the name of your project. Vue CLI will then create a new directory with the specified name and set up a new Vue project inside it.

What is a Vue instance and how do I create one?

A Vue instance is an object that Vue.js creates based on your Vue configuration. It’s the root of your Vue app and contains all the methods and data for your app. To create a Vue instance, you use the “new Vue()” syntax, passing in an object that contains your Vue configuration.

How do I add Vue.js to an existing project?

To add Vue.js to an existing project, you can either add a script tag to your HTML file that points to the Vue.js library, or you can install Vue.js using npm and import it into your JavaScript file. The method you choose depends on the complexity of your project and your personal preference.

How do I use Vue.js components?

Vue.js components are reusable pieces of your Vue app that encapsulate their own structure, style, and behavior. To use a Vue component, you first need to define it using “Vue.component()”, then you can use it in your Vue app’s template as a custom element.

How do I handle user input in Vue.js?

In Vue.js, you can handle user input using v-model and v-on directives. The v-model directive creates two-way data binding between your form input and your Vue data, while the v-on directive listens for DOM events like click, input, or submit and runs a method when they occur.

How do I conditionally render elements in Vue.js?

In Vue.js, you can conditionally render elements using the v-if, v-else, and v-show directives. The v-if directive renders an element if its expression returns true, the v-else directive renders an element if the previous v-if expression returns false, and the v-show directive toggles the display CSS property of an element based on its expression.

How do I loop through lists in Vue.js?

In Vue.js, you can loop through lists using the v-for directive. The v-for directive binds an array to a list of elements, rendering an element for each item in the array. You can use it with the “item in items” syntax, where “items” is your array and “item” is the alias for the array element.

Matt MickiewiczMatt Mickiewicz
View Author

Matt is the co-founder of SitePoint, 99designs and Flippa. He lives in Vancouver, Canada.

vue
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week