Search
Learn
Share

Split your Vue.js script into multiple files

Published by Profile Image LGK on 26 October, 2016
498 views
You are using Vue.js and your site has multiple pages. But your model for contact form information should only be available on the contact.html site.

So this is how you do it.

contact.html
<!DOCTYPE html>
<html>
<head>
<!-- stylesheets and stuff... -->
</head>

<body>
<div id="app">
<h1>{{appTitle}}</h1>

<h2>Contact</h2>
<form v-on:submit="sendContactForm()">
<label>Email</label>
<input type="text" v-model="contactForm.email">

<label>Name</label>
<input type="text" v-model="contactForm.name">

<label>Message</label>
<textarea v-model="contactForm.message"></textarea>

<button type="submit">Send</button>
</form>
</div>

<script src="vue.js"></script>

<script src="global.js"></script>

<!-- Only needs to be included on contact.html. -->
<script src="contact.js"></script>

<script src="main.js"></script>
</body>
</html>

global.js
<!-- Set data and methods that should be available on each page. -->
var globalVue = {
data: {
appTitle: "Hello World"
},
methods: {}
};

contact.js
<!-- Extend the global settings by data and methods that should only be available at contact.html. -->

globalVue.data.contactForm = {
email: null,
name: null,
message: null
};

globalVue.methods.sendContactForm = function() {
// send it ...
// Use app.contactForm to get access to the model data.
};

main.js
<!-- Finally create the Vue instance and set the data and methods -->
var app = new Vue({
el: '#app',
data: globalVue.data,
methods: globalVue.methods
});