Vue Widgets

Vue & Drupal Integration
Tagged: jsTuesday, October 1, 2019

Integrating Vue.js into Drupal or any CMS

I needed any easy solution to incorporating Vue.js features into an existing CMS. My particular CMS is Drupal but this can be used on any existing project to work Vue.js applications into sites.

Limitations of the Script Tag Approach

I started off using script tags and pasting Vue.js directly as HTML into the CMS. This worked fine for small interactive things, but as with many projects it just got more complex as features were added. Components, Sass, Imports and many other things can all be done with the script tag approach but its much harder and finding examples is harder if you get stuck. I missed webpack and the Vue CLI!

Vue Widgets to the Rescue

While searching for an answer I stumbled upon this post Vuidget - How to create an embeddable Vue.js widget with vue-custom-element which was a great guide to getting started.

I won't repeat the post, but I did want to clarify a few things that were not clear in that post.

After the npm install webpack --save you have to create a vue.config.js file to customize webpack not to chunk and hash filenames. So here is the contents of your vue.config.js with the added filenameHashing: false

const webpack = require('webpack')
module.exports = {
  configureWebpack: {
    plugins: [
      new webpack.optimize.LimitChunkCountPlugin({
        maxChunks: 1
      })
    ]
  },
  chainWebpack:
    config => {
      config.optimization.delete('splitChunks')
    },
    filenameHashing: false
}

I then used GitHub Actions to create a build and pushed it up to Azure.

Including it in Drupal or any CMS

Now with the Vue.js app built and hosted you can simply paste in code similar to the below by looking at the final index.html in your /dist folder.

<link href="https://vueapp.z13.web.core.windows.net/css/app.css" rel="stylesheet">
<vue-widget></vue-widget>
<script src="https://vueapp.z13.web.core.windows.net/js/app.js"></script>

And what is really awesome is you can even pass this widget optional props so that it can accept different data or configuration. Here I am passing it a data prop that the vue-widget will use.

<link href="https://vueapp.z13.web.core.windows.net/css/app.css" rel=stylesheet>
<vue-widget data="5,6,7,6,8,9"></vue-widget>
<script src="https://vueapp.z13.web.core.windows.net/js/app.js"></script>

Then since this data='5,6,7,6,8,9' is a string before you can use it you will have to transform it into an array. I did this on the created life cycle hook and just created a simple method helper.

created: function created() {
  let propData = this.stringToArray(this.data)
  // now do something with propData
},
methods: {
  stringToArray(value){
    // When widget is passed a string convert it to an array
    return value.split(",")
  }
}