Vue.js Tutorial: Getting Started & 10 Best Practices

    Matt Mickiewicz
    Share

    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.

    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!