UPDATE (2020-05-10)
Discover How to Use ES6 Modules Without Webpack
When working with ES6, avoid manually inserting your main.js
into index.html
as this task will be taken care of by Webpack. The simplest Vue tutorial typically involves the following steps:
- npm install -g vue-cli
- vue init webpack my_project
- npm run dev (start developing, available result at http://localhost:8080)
- npm run build (result available inside the
./dist
folder of your project)
Make sure to import Vue in the correct way:
import Vue from 'vue';
and not like this
import Vue from '../../node_modules/vue';
EDIT
If you prefer a beginner-friendly approach without using Webpack and single-file Vue components, start like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
<title>My beginners project</title>
<link rel="stylesheet" type="text/css" href="/assets/css/styles.css" />
</head>
<body>
<div id="app">
<router-view></router-view>
</div>
<!-- templates for your components -->
<template id="login">
<div>test</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dea8abbb9eecf0ebf0efe9">[email protected]</a>/dist/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfc9cada92cdd0cacbdacdff8c918f918e">[email protected]</a>/dist/vue-router.js"></script>
<!-- code for your components -->
<script type="text/javascript" src="/app/login.js"></script>
<!-- Vue Root component should be last -->
<script type="text/javascript" src="/app/app.js"></script>
</body>
</html>
Your /app/app.js
file will have the following structure:
var badRoute = Vue.component('bad-route', {
template: '<div id="bad_route"><h1>Page Not Found</h1><p>Sorry, but the page you were trying to view does not exist.</p></div>'
});
var vue_router = new VueRouter({
base: '/app'
, mode: 'hash'
, routes: [{
path: '/'
, redirect: '/login'
}, {
path: '/login'
, component: loginForm
, name: 'LOGIN'
}, {
path: '*', // should be last, otherwise matches everything
component: badRoute
, name: 'NOT FOUND'
}]
});
// Main application
var vue_app = new Vue({
router: vue_router
, })
.$mount('#app');
The component script in your /app/login.js
file will look similar to this:
var loginForm = Vue.component('login-form', {
template: '#login', // must match the ID of the template tag
data: function() {
var formData = {
username: ''
, password: ''
, };
return formData;
}
, methods: {}
});