Vue has grown by leaps and bounds over the last couple years, and overtook Angular as the #2 frontend framework in 2018. According to the State of JS survey, Vue is the #1 frontend framework that isn’t associated with a serial bad actor, which makes it worth learning if you’re serious about going Facebook-free. In this article, I’ll walk through building a simple form with Vue.

Getting Started

One of the major benefits of Vue is that you can get started in vanilla JavaScript, with no outside npm modules or new languages.

The easiest way to get started with Vue is including it via script tag. However, for educational purposes, this article will npm install the vue npm package and create a bundle with webpack.

The first step is to npm install a couple packages. In addition to vue and webpack, install serve to spin up a lightweight web server.

npm install vue@2.6 webpack@4.x webpack-cli@3.x serve@10.x

Create an index.html file that loads a main.js bundle. The #content div is the element Vue will render into, and name-form is a custom component that we’ll add to Vue.

<html>
  <head><title>Vue Form Example</title></head>

  <body>
    <div id="content">
      <name-form></name-form>
    </div>

    <script type="text/javascript" src="dist/main.js"></script>
  </body>
</html>

Here’s a minimal Webpack config file webpack.config.js that will take a main.js file, which contains the definition of the name-form component, and create a standalone bundle dist/main.js.

module.exports = {
  mode: process.env.NODE_ENV || 'production',
  entry: {
    main: './main.js'
  },
  target: 'web',
  output: {
    path: `${process.cwd()}/dist`,
    filename: '[name].js'
  }
};

Importing Vue via require() is easy, but not quite trivial. Here’s how you import Vue with require():

const Vue = require('vue/dist/vue.esm').default;

Here’s the full main.js file. The main.js file imports Vue, defines the name-form component to show ‘Hello, World’, and creates a new Vue instance bound to the #content div.

const Vue = require('vue/dist/vue.esm').default;

Vue.component('name-form', {
  template: `
    <h1>Hello, World</h1>
  `,
});

new Vue({ el: '#content' });

#vue #javascript #web-development #programming #developer

Building a Simple Form with Vue.js
1.70 GEEK