Chapter 20 - Effortless Vue.js Setup: Master Project Creation with Vue CLI

Vue CLI simplifies Vue.js project setup. It offers customizable templates, component structure, and easy integration of tools like Vuex and Vue Router for efficient development.

Chapter 20 - Effortless Vue.js Setup: Master Project Creation with Vue CLI

Setting up a Vue.js project with Vue CLI is a breeze, and I’m excited to walk you through the process. As someone who’s been working with Vue for years, I can tell you it’s one of the most developer-friendly frameworks out there. Let’s dive in and get your project up and running!

First things first, you’ll need to have Node.js installed on your machine. If you haven’t already, head over to the official Node.js website and download the latest version. Once that’s done, you’re ready to rock and roll with Vue CLI.

Vue CLI is a powerful tool that helps you kickstart your Vue.js projects. It’s like having a personal assistant who sets up everything for you, saving you tons of time and headaches. To install Vue CLI globally on your machine, open up your terminal and run this command:

npm install -g @vue/cli

This might take a minute or two, so grab a coffee while you wait. Once it’s finished, you’ll have the Vue CLI tool available system-wide.

Now, let’s create our project. Think of a cool name for your app – I’ll use “awesome-vue-app” for this example. Navigate to the directory where you want to create your project and run:

vue create awesome-vue-app

Vue CLI will now ask you a series of questions to customize your project setup. For beginners, I recommend going with the default preset, which includes Babel and ESLint. It’s a great starting point, and you can always add more features later.

If you’re feeling adventurous, you can choose the “Manually select features” option. This lets you pick and choose exactly what you want in your project. You might see options like TypeScript, PWA support, Vue Router, Vuex, and testing tools. Don’t worry if you’re not sure about these – you can always add them later if you need them.

Once you’ve made your selections, Vue CLI will work its magic and set up your project. This process usually takes a couple of minutes, depending on your internet speed and the options you’ve chosen.

When it’s done, you’ll see a success message in your terminal. Congrats! You’ve just created your Vue.js project. But we’re not done yet – let’s dive into the project structure and get it running.

First, navigate into your project folder:

cd awesome-vue-app

Now, let’s take a look at what Vue CLI has created for us. Here’s a breakdown of the main files and folders:

The src folder is where the magic happens. It contains your application’s source code. Inside, you’ll find:

  • main.js: This is the entry point of your app. It creates the Vue instance and mounts it to the DOM.
  • App.vue: This is your root component. Think of it as the skeleton of your app.
  • components folder: This is where you’ll put all your Vue components.
  • assets folder: This is for storing static assets like images and fonts.

Outside the src folder, you’ll see:

  • public folder: This contains the index.html file and other static assets that don’t need processing.
  • package.json: This file lists your project dependencies and scripts.
  • babel.config.js: Configuration for Babel, which helps ensure your modern JavaScript works in older browsers.
  • .eslintrc.js or .eslintrc.json: ESLint configuration for maintaining code quality.

Now, let’s get this app running! In your terminal, type:

npm run serve

This command starts a development server. Once it’s ready, you’ll see a message with a local URL (usually http://localhost:8080). Open that in your browser, and voila! You should see the Vue.js welcome page.

Pretty cool, right? But let’s make it our own. Open up src/App.vue in your favorite code editor. You’ll see three sections: <template>, <script>, and <style>. This is the structure of a Vue single-file component.

Let’s modify the template section. Replace the existing content with this:

<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
  </div>
</template>

Now, update the script section:

<script>
export default {
  name: 'App',
  data() {
    return {
      title: 'Welcome to My Awesome Vue App!',
      message: 'This is going to be amazing!'
    }
  }
}
</script>

Save the file and check your browser – it should update automatically. You’ve just created your first custom Vue component!

Let’s take it a step further and create a new component. In the src/components folder, create a new file called HelloUser.vue. Open it up and add this code:

<template>
  <div class="hello-user">
    <h2>Hello, {{ name }}!</h2>
    <button @click="changeName">Change Name</button>
  </div>
</template>

<script>
export default {
  name: 'HelloUser',
  data() {
    return {
      name: 'Vue Developer'
    }
  },
  methods: {
    changeName() {
      this.name = 'Awesome ' + this.name
    }
  }
}
</script>

<style scoped>
.hello-user {
  margin-top: 20px;
}
</style>

This component displays a greeting and has a button to change the name. Now, let’s use this component in our App.vue. Update your App.vue file like this:

<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
    <HelloUser />
  </div>
</template>

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

export default {
  name: 'App',
  components: {
    HelloUser
  },
  data() {
    return {
      title: 'Welcome to My Awesome Vue App!',
      message: 'This is going to be amazing!'
    }
  }
}
</script>

Save both files and check your browser. You should now see your new component rendered below the welcome message, complete with a working button!

Now that we have a basic app structure, let’s talk about some best practices and tips for organizing your Vue.js project.

First, keep your components small and focused. Each component should do one thing and do it well. This makes your code more reusable and easier to maintain. If a component starts getting too big or complex, consider breaking it down into smaller sub-components.

Second, use props for parent-child component communication. Props allow you to pass data from a parent component to a child component. For example, we could modify our HelloUser component to accept a name prop:

<template>
  <div class="hello-user">
    <h2>Hello, {{ userName }}!</h2>
    <button @click="changeName">Change Name</button>
  </div>
</template>

<script>
export default {
  name: 'HelloUser',
  props: {
    userName: {
      type: String,
      default: 'Vue Developer'
    }
  },
  methods: {
    changeName() {
      this.$emit('nameChanged', 'Awesome ' + this.userName)
    }
  }
}
</script>

And then in App.vue:

<template>
  <div id="app">
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
    <HelloUser :userName="name" @nameChanged="updateName" />
  </div>
</template>

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

export default {
  name: 'App',
  components: {
    HelloUser
  },
  data() {
    return {
      title: 'Welcome to My Awesome Vue App!',
      message: 'This is going to be amazing!',
      name: 'Vue Developer'
    }
  },
  methods: {
    updateName(newName) {
      this.name = newName
    }
  }
}
</script>

This demonstrates not only passing data down via props, but also emitting events up to the parent component.

As your app grows, you might want to consider adding Vuex for state management. Vuex provides a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. To add Vuex to your project, you can run:

vue add vuex

This will install Vuex and create a store directory in your src folder. Here’s a simple example of how you might use Vuex:

// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  },
  getters: {
    doubleCount: state => state.count * 2
  }
})

You can then use this store in your components:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'

export default {
  computed: {
    ...mapState(['count']),
    ...mapGetters(['doubleCount'])
  },
  methods: {
    ...mapMutations(['increment']),
    ...mapActions(['incrementAsync'])
  }
}
</script>

This is just scratching the surface of what you can do with Vuex, but it’s a powerful tool for managing state in larger applications.

As your project grows, you might also want to add routing. Vue Router is the official router for Vue.js. You can add it to your project by running:

vue add router

This will install Vue Router and set up a basic routing structure in your app. It will create a router directory in your src folder with an index.js file. Here’s what a basic router setup might look like:

// src/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

You can then use router-link components to navigate between routes:

<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </nav>
    <router-view/>
  </div>
</template>

The <router-view> component is where your route components will be rendered.

When it comes to styling your Vue.js app, you have several options. You can use regular CSS, or take advantage of preprocessors like SASS or LESS. Vue CLI makes it easy to add these to your project. For example, to add SASS support, you can run:

vue add sass

This will install the necessary dependencies and update your webpack config to handle .scss files. You can then use SASS in your component styles:

<style lang="scss">
$primary-color: #