VueJS 101 for CFML Devs
I’ve been stumbling across a fair few developers recently who like the idea of using VueJS, but are not sure how to get started. VueJS can be used to build whole applications, but sometimes the requirement is to just build something within an existing CFML page to make the UI more dynamic and user-friendly. This set of examples is aimed at those of you who want to dip your toes into VueJS and might have an existing CFML application that you want to enhance.
We’re mainly going to focus on the question I get the most, which is “how to do I get my data from CFML to VueJS?”.
All the code is available on Github, but we’ll go through some of the key concepts each example brings. The setup is simple, one index file, and one “remote” cfm/cfc file which we’ll call via VueJS.
VueJS 101 example 1 – Simple Message
Our aim here is simple – pressing the button should do a request to our CFML page, and return a message.
Let’s look at the index.cfm first.
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
The first thing to note is we’re just going to use regular old script tags to import Vue. We’ll also import Axios, which is a library we’ll use to make our AJAX requests.
<div id="app">
{{ message }}
<br />
<button @click="getData">Get Message</button>
</div>
Then, we’ve got a div with an id of “app”: this is our Vue instance will operate within. Our JS markup uses `{{}}` to denote the value of a variable, and our button has an `@click` handler which calls the corresponding method in the methods block.
<script> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, methods: { getData: function() { axios.get('remote.cfm') .then(function(response) { app.message = response.data.message; }) .catch(function(error) { console.log(error); }); } } }); </script>
Our main script block initializes the Vue instance and uses `el` to bind it to the div.
The data object is where you can define variable defaults; we’ll use a simple message variable to store the message we get back from our request.
Our methods block contains a single method, `getData()`, which is called when the button is clicked. It uses the Axios library to make a request to our CFML page and then sets the `message` variable to the response. If anything goes wrong, then the catch block will output the error to the console.
Our remote.cfm couldn’t be simpler;
header name="Content-Type" value="application/json"; data = { "message" = "Hi from CFML! The time is #now()#" }; writeOutput(serializeJSON(data));
We set the return type as JSON, create a new struct with a single field called “message”, and then return that via serializeJSON();
We can monitor the response in chrome dev tools.