AEM and VueJS integration part I

April 18, 2018    aem vue javascript integration tutorial


Why VueJS

I guess that we are all bored with jQuery at the beginning of 2018. There are many modern frameworks we want to use and to try (React, Angular). Nevertheless it is quite complicated to integrate them into AEM and here comes VueJS. It is not monolithic and could be used like a small library to add a bit of action to your AEM based site

Vue intro

  • Please take a look at the VueJS intro documentation
  • Awesome blog post which describes all ways how he can define Vue component template blog post

Integration

working project could be found here

Step 1 - Add VueJs script

Let’s do it quite straightforward for now and just add it from CDN.

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

I have added it to footlibs.html of my page component before our project clientlibs.

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<sly data-sly-use.clientLib="/libs/granite/sightly/templates/clientlib.html" data-sly-call="${clientLib.js @ categories='aem-ktln.all'}" data-sly-unwrap/>

Step 2 - Create Simple Component

Create Component Structure

component structure

Add component markup

In counter.html let’s add this code.

<div class="counter__content">
    <counter number="${properties.number}" button-text="${component.name}"/>
</div>

Here the number will be derived from a component’s properties and the button text will be the component’s name

Vue component itself

In counter.js we will add the following code.

Vue.component('counter', {
    props: ['number', 'buttonText'],
    template: `<div>
                 <button @click="increment">{{buttonText}}</button>
                 <h3>{{counter}}</h3>
               </div>`,
    methods: {
        increment() {
            this.counter++;
        }
    },
    data() {
        return {
            counter: Number.parseInt(this.number)
        }
    }

});

Here we can see: * registered counter component with the tag * incoming properties ‘number’, ‘buttonText’ * methods and data

But we still have one problem: we need to tell Vue where it should render this counter component. Therefore let’s add the initial code to the component.js

[].forEach.call(document.getElementsByClassName('counter__content'), el => {
    new Vue({el: el})
})

All is ready, let’s deploy and check

Step 3 - Check the results

component on the page

You can see that instead of a number we have ‘NaN’. This is because we have not configured the number in the component’s dialog. Let’s fix this.

  • Open the dialog
  • Set the number, eg. to ‘1’
  • Save

dialog

Now open the page in the ‘view as published’ mode

counter changes

Conclusion

It was quite simple to integrate Vue, but it is not a production-ready solution, therefore stay tuned for the next post with NPM and Webpack integration.




comments powered by Disqus